计算滚动周期

Count over a rolling period

。这个问题与我原来的问题类似,但有一个额外的变化,我想查看一组 运行 期间的先前服务计数。所以说我有一个 table:

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)

但这似乎不太奏效..

这是一个基于您之前问题中的表格的查询(为方便起见,我已将其加入 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