前几个月的复合值

问题描述 投票:0回答:1

我的经理要我统计每个有订单的中心。如果中心在过去两个月内下达了一个订单,则该中心在下达订单当月起的接下来两个月内被视为活跃。示例:如果中心“AR238”于 2 月 1 日下了订单,则该订单在接下来的两个月内被视为有效。因此,如果三月或四月没有再下订单,它会一直活跃到四月底。我正在尝试计算每个月每个活跃中心的数量,并与前几个月相结合。因此,如果一个中心在二月份下了订单,我需要能够计算二月、三月和四月的订单。请协助了解如何做到这一点。另外,我需要将查询包含到我已经写出的查询中。此查询只会向我原始查询中已有的表添加一个额外的列。我将在下面发布我的原始查询。

WITH active_centers AS (
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))

--该查询返回每个月、每个月的订单量以及每个月的活跃中心。我在此查询中拥有的活动中心仅对中心进行一次计数。我想要一个额外的列来计算每个中心的一月、二月、三月(如果它在一月份下订单的话)。如果该中心在二月份再次下订单,它将重置周期,我们现在将二月,三月,四月计算一次。我试图添加的额外列基本上是复合的。

sql-server sql-server-2022
1个回答
0
投票

这并不能让您的查询按照您希望的方式保持完整,但我认为您会想要这样的东西。首先,您的查询版本不会处理超过 12 个月的数据。要获得前两个月的数据,如果我理解要求,您还必须在报告范围开始之前回顾一下。由于

count(distinct)
操作,您将无法预聚合,因此我认为子查询或交叉应用是完成这部分制表的方法:

 with active_centers as (
    select
        datediff(month, '2024-01-01', DmeOrderDate) as MonthNum,
        DmeOrderDate, CenterCode, DmeOrderNumberDisplay
    from AtHome.Reporting.WoundQOrderDetails as w
        left join AtHome.Reporting.DimCenter c on c.CenterSK = w.CenterSK
    where DmeOrderDate between dateadd(month, -2, '2024-01-01') and getdate()
        and DmeSignedByProvider = 1 and OrderType = 'NPWT' and CenterCode is not null
), report_dates(report_date) as (
    select distinct datetrunc(DmeOrderDate) from active_centers where MonthNum >= 0
)
select report_date, NPWT_Order_Volumn, NPWT_Active_Centers
from report_dates as d cross apply (
    select count(distinct DmeOrderNumberDisplay), count(distinct CenterCode)
    from active_centers as c
    where c.DmeOrderDate >= dateadd(month, -2, d.report_month) and
          c.DmeOrderDate  < dateadd(month,  1, d.report_month)
) as cnt(NPWT_Order_Volume, NPWT_Active_Centers)
order by report_date;

由于订单日期列上可能有一个索引,我希望这将在循环中有效地使用该索引。

© www.soinside.com 2019 - 2024. All rights reserved.