SQL 每年重置频率计数

SQL Frequency Count resetting for each year

我想根据日期的顺序计算变量出现的频率 - 我可以做到。但我希望每年重置频率计数 - 我无法重置它。

table 如下所示,但我手动添加了频率:

Date / Variable / Year / Frequency
2019-01-01 / blue / 2019 / 1
2019-01-15 / blue / 2019 / 2
2019-01-01 / red / 2019 / 1
2019-04-01 / blue / 2019 / 3
2019-06-01 / red / 2019 / 2
2020-01-01 / blue / 2020 / 1
2020-04-01 / red / 2020 / 1
2020-01-21 / blue / 2020 / 2
2020-06-01 / blue / 2020 / 3
2020-08-01 / red / 2020 / 2
2021-01-21 / blue / 2021 / 1
2021-02-21 / red / 2021 / 1

这是我进行原始计数的方式,但这忽略了每年的重置:

UPDATE A
SET A.Frequency = 
(SELECT COUNT(*) FROM #TableB B 
WHERE B.Date <= A.Date 
AND B.Variable = A.Variable)
FROM #TableA A

我试过添加 WHERE 子句,即

WHERE A.Date BETWEEN '2019-01-01' AND '2019-12-31'

并添加年份列并以这种方式进行限制,即

UPDATE A
SET A.Frequency = 
(SELECT COUNT(*) FROM #TableB B 
WHERE B.Date <= A.Date 
AND B.Variable = A.Variable
AND B.Year = '2020')
FROM #TableA A

如有任何提示,我们将不胜感激!谢谢

您可以使用 row_number()

DBFiddle

select a.[date], 
       a.variable, 
       a.year,
       row_number() over (partition by a.variable, a.year order by [date]) AS frequency
from   tableA a
order by a.id

结果

date        variable    year    frequency
2019-01-01  blue        2019    1
2019-01-15  blue        2019    2
2019-01-01  red         2019    1
2019-04-01  blue        2019    3
2019-06-01  red         2019    2
2020-01-01  blue        2020    1
2020-04-01  red         2020    1
2020-01-21  blue        2020    2
2020-06-01  blue        2020    3
2020-08-01  red         2020    2

编辑
如何在更新中使用它:

update aa
set    aa.frequency = aaa.frequency
from   tableA aa
  inner join ( select a.[date], a.variable, a.year,
                      row_number() over (partition by a.variable, a.year order by [date]) AS frequency
               from   tableA a
             ) aaa on aa.[date] = aaa.[date]
                  and aa.variable = aaa.variable
                  and aa.year = aaa.year

this DBFiddle