【问题标题】:Count over a rolling period在滚动周期内计数
【发布时间】:2020-05-04 06:52:41
【问题描述】:

This is a follow-up to my earlier question。这个问题与我原来的问题类似,但有一个额外的转折,我想查看在设定的运行期间内先前服务的计数。所以说我有一张桌子:

id | client |date    | service
1  |     1  | 1/2010 | A
2  |     1  | 1/2011 | A
3  |     1  | 1/2012 | A
4  |     1  | 1/2015 | A

我可以使用ROW_NUMBER() OVER (PARTITION BY client, service ORDER BY date) - 1 计算每个服务在给定日期之前执行了多少次,但是我如何进行查询以显示在给定日期之前以及在任何给定滚动期内执行的服务数量?

假设我想知道仅在过去 2 年中完成了多少 A 类服务。预期的结果是:

client |date    | no of prior services
    1  |1/2010  | 0
    1  |1/2011  | 1
    1  |1/2012  | 2
    1  |1/2015  | 0 - no earlier services within the last two years.

我拥有的是类似的东西

select table0.*, count(table1.date)
from table table0
left outer join table table1
  ON table0.client = table1.client
 AND table0.date > table1.date
 AND table1.date > DATEADD(year, -3, table0.date)

但这似乎不太奏效..

【问题讨论】:

    标签: sql-server-2016 rolling-computation


    【解决方案1】:

    这是基于您之前问题中的表格的查询(为方便起见,我已将其加入 CTE)。

    WITH CTE AS (
      SELECT b.bill_id, b.person_id, b.bill_date, bd.service_type
      FROM billing b
      JOIN billing_detail bd ON bd.bill_id = b.bill_id
    )
    SELECT c1.person_id, c1.bill_date, c1.service_type,
           COUNT(c2.bill_date) AS prior_services
    FROM CTE c1
    LEFT JOIN CTE c2 ON c2.person_id = c1.person_id
                    AND c2.service_type = c1.service_type
                    AND c2.bill_date >= DATEADD(YEAR, -2, c1.bill_date) 
                    AND c2.bill_date < c1.bill_date
    GROUP BY c1.person_id, c1.bill_date, c1.service_type
    

    Demo on dbfiddle

    【讨论】:

    • 谢谢,昨天我无法正确获取日期逻辑,大脑无法正常工作。我还使用 CTE 在我的实际查询中加入表。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 2013-06-14
    • 1970-01-01
    • 2021-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-25
    相关资源
    最近更新 更多