我有一张大桌子,其片段如下:
ID | Archive | Open Account Date
Bob | May 2018 | Jan 2018
Bob | June 2018 | Jan 2018
Bob | June 2018 | Mar 2018
Bob | July 2018 | Jan 2018
Bob | July 2018 | Mar 2018
我只想计算“鲍勃”在每个(存档日期)和每个(存档日期1)拥有的不同未结帐户的数量。
所以,对于2018年6月:
At Archive Date, Bob has 2.
At Archive Date-1, Bob only has 1.
这是我尝试过的:
-因为数据太多,而不仅仅是“鲍勃”,我有点困惑。 这对于在特定存档日期计算所有未清帐户日期是有意义的: -COUNT(未结帐户日期)超过(按ID按归档顺序排序)为CurrentArchive_Counts
但是我不能将延迟与Count混合使用,所以我认为这不起作用: -Count(LAG(开户日期,1)OVER(按ID按归档对ID进行分区))为PreviousArchive_Counts ??
答案 0 :(得分:0)
您不需要滞后:。查看分区函数的"Row/Range"子句。查看示例D。
您将需要遵循以下原则:
SELECT *, COUNT() OVER( PARTITION BY ID ORDER BY Archive ROWS BETWEEN CURRENT ROW AND UNBOUNDED PRECEDING ) AS AccountsNum,
COUNT() OVER( PARTITION BY ID ORDER BY Archive ROWS BETWEEN 1 PRECEEDING AND UNBOUNDED PRECEDING ) AS LastArchiveAccountsNum,
FROM [table]