[英]Need YTD and MTD calculations in SQL
Date Amt ytd mtd
01-Jan-21 1 2 2
01-Jan-21 1 2 2
02-Jan-21 1 3 3
03-Jan-21 1 4 4
01-Feb-21 1 5 1
02-Feb-21 1 6 2
03-Feb-21 1 7 3
04-Feb-21 1 8 4
05-Feb-21 1 9 5
01-Mar-21 1 10 1
02-Mar-21 1 11 2
03-Mar-21 1 12 3
04-Mar-21 1 13 4
01-Apr-21 1 14 1
02-Apr-21 1 15 2
03-Apr-21 1 16 3
01-May-21 1 17 1
02-May-21 1 18 2
03-May-21 1 19 3
04-May-21 1 20 4
05-May-21 1 21 5
06-May-21 1 22 6
I have the first two columns (Date, Amt) and i need the YTD and MTD columns in MS SQL so that i can show the above table.我有前两列(日期、时间),我需要 MS SQL 中的 YTD 和 MTD 列,以便我可以显示上表。
Seems like a rolling COUNT OVER was used to calculate the ytd & mtd in the Oracle source.似乎使用滚动计数来计算 Oracle 源中的 ytd 和 mtd。
(Personally, I would prefere RANK or DENSE_RANK) (就个人而言,我更喜欢 RANK 或 DENSE_RANK)
And since Oracle datestamps can be casted to a DATE as-is.并且由于 Oracle 日期戳可以按原样转换为 DATE。
SELECT [Date], Amt, ytd = COUNT(*) OVER (ORDER BY CAST([Date] AS DATE)), mtd = COUNT(*) OVER (PARTITION BY EOMONTH(CAST([Date] AS DATE)) ORDER BY CAST([Date] AS DATE)) FROM your_table ORDER BY CAST([Date] AS DATE)
Date![]() |
Amt![]() |
ytd![]() |
mtd ![]() |
---|---|---|---|
01-Jan-21 ![]() |
1 ![]() |
2 ![]() |
2 ![]() |
01-Jan-21 ![]() |
1 ![]() |
2 ![]() |
2 ![]() |
02-Jan-21 ![]() |
1 ![]() |
3 ![]() |
3 ![]() |
03-Jan-21 ![]() |
1 ![]() |
4 ![]() |
4 ![]() |
01-Feb-21 ![]() |
1 ![]() |
5 ![]() |
1 ![]() |
02-Feb-21 ![]() |
1 ![]() |
6 ![]() |
2 ![]() |
03-Feb-21 ![]() |
1 ![]() |
7 ![]() |
3 ![]() |
04-Feb-21 ![]() |
1 ![]() |
8 ![]() |
4 ![]() |
05-Feb-21 ![]() |
1 ![]() |
9 ![]() |
5 ![]() |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.