按年份划分历史数据

时间:2017-09-12 21:05:21

标签: sql-server

我无法使用my partition子句

在2016年和2017年之间分隔数据
select *, COUNT(*) OVER(PARTITION BY [Customer Number] ORDER BY [Week Ending]) FROM [dbo].[mytable]

我的输出给了我这个:

Week Ending        Customer Number
Apr  5 2017 12:00AM   11
Apr  6 2016 12:00AM   2
Apr 12 2017 12:00AM   11
Apr 13 2016 12:00AM   4
Apr 19 2017 12:00AM   11
Apr 20 2016 12:00AM   6
Apr 26 2017 12:00AM   11
Apr 27 2016 12:00AM   11
Aug  2 2017 12:00AM   9
Aug  3 2016 12:00AM   11
Aug  9 2017 12:00AM   11

基本上,我想计算一下2016年和2017年客户#出现分区的次数

1 个答案:

答案 0 :(得分:0)

通过...将年份添加到分区中,理想情况下也可以选择年份,以便了解哪一年与哪一年相符。

select 
    *, 
    TheYear = DATEPART(year,[Week Ending]),
    TheYearlyCount = COUNT(*) OVER(PARTITION BY [Customer Number], DATEPART(year,[Week Ending]) ORDER BY [Week Ending]) 
FROM [dbo].[mytable]