I have a set of historical data, let’s say from the year 2000 stored in table A. The data structure of the table simply composes of 2 column, the date dt and item
dt, item
1/20/2000, A1
1/20/2000, A2
1/20/2000, A3
....
6/1/2024, A1
---
How do I calculate the historic count of each item for the last 2 years?
In other word, I would like to see the results like this:
202406, Count of A1 until 6/1/2024 since 1/1/2000
202406, Count of A2 until 6/1/2024 since 1/1/2000
202406, Count of A3 until 6/1/2024 since 1/1/2000
202405, Count of A1 until 5/1/2024 since 1/1/2000
202405, Count of A2 until 5/1/2024 since 1/1/2000
202405, Count of A3 until 5/1/2024 since 1/1/2000
...
202206, Count of A1 until 6/1/2022 since 1/1/2000
202206, Count of A2 until 6/1/2022 since 1/1/2000
202206, Count of A3 until 6/1/2022 since 1/1/2000
I can easily group and count the item in a specific month using this:
select 202406, count(item)
from table A
where datetime < 6/1/2024
group by left(convert(varchar,dt,112),6)
I can also list the 24 past months since today
select dt2=format(dateadd(month,2-n,getdate()),'yyyyMM')
from
(
select top (24) n=row_number() over (order by (select null))
from sys.object)
)
But I can not combine my 2 sql statements above to get the result I want.
Please help.