我的经理要我统计每个有订单的中心。如果中心在过去两个月内下达了一个订单,则该中心在下达订单当月起的接下来两个月内被视为活跃。示例:如果中心“AR238”在二月份下了订单,那么该订单将被视为在接下来的两个月内有效。因此,如果三月或四月没有再下订单,它会一直活跃到四月。我正在尝试计算每个月每个活跃中心的数量,并与前几个月相结合。因此,如果一个中心在二月份下了订单,我需要能够计算二月、三月和四月的订单。请协助如何做到这一点。
SELECT DateName( month , DateAdd( month , MONTH(dmeorderdate) , 0 ) - 1 ) as Month, count(distinct
DmeOrderNumberDisplay) as NPWT_Order_Volume, count(distinct CenterCode) as NPWT_Active_Centers
FROM [AtHome].[Reporting].[WoundQOrderDetails] w
left join[AtHome].[Reporting].[DimCenter] c on c.CenterSK = w.CenterSK
where DmeOrderDate between '2024-01-01' and GETDATE()
and DmeSignedByProvider = 1
and OrderType = 'NPWT'
and CenterCode is not null
group by DateName( month , DateAdd( month , MONTH(dmeorderdate) , 0 ) - 1 ),MONTH(dmeorderdate)
order by MONTH(dmeorderdate)
要计算每个月的每个活跃中心,并与前几个月进行复合,您可以使用窗口函数和条件聚合的组合。这是更新的查询:
WITH ActiveCenters AS (
SELECT
CenterCode,
DATEADD(mm, 2, DATE_TRUNC('month', dmeorderdate)) AS ActiveUntil
FROM
[AtHome].[Reporting].[WoundQOrderDetails] w
LEFT JOIN
[AtHome].[Reporting].[DimCenter] c ON c.CenterSK = w.CenterSK
WHERE
DmeOrderDate BETWEEN '2024-01-01' AND GETDATE()
AND DmeSignedByProvider = 1
AND OrderType = 'NPWT'
AND CenterCode IS NOT NULL
)
SELECT
DATE_NAME(month, DATEADD(month, MONTH(a.ActiveUntil), 0) - 1) AS Month,
COUNT(DISTINCT a.CenterCode) AS NPWT_Active_Centers
FROM
ActiveCenters a
CROSS JOIN (
SELECT DISTINCT DATE_TRUNC('month', dmeorderdate) AS Month
FROM
[AtHome].[Reporting].[WoundQOrderDetails]
WHERE
DmeOrderDate BETWEEN '2024-01-01' AND GETDATE()
) m
WHERE
a.ActiveUntil >= m.Month
GROUP BY
DATE_NAME(month, DATEADD(month, MONTH(a.ActiveUntil), 0) - 1)
ORDER BY
MONTH(a.ActiveUntil)