我的表格中包含ID
,Title
,Date
,Amount
列。
我需要根据Title
,Date
获取针对每笔交易的MTD,YTD金额值。
之前有没有人这样做过?
答案 0 :(得分:4)
Select t.title, t.Date,
Sum(y.Amount) YTD,
Sum(m.Amount) MTD
From table t
join table y
on y.Title = t.Title
and datediff(year, y.Date, t.Date) = 0
and y.Date <= t.Date
join table m
on m.Title = t.Title
and datediff(month, m.Date, t.Date) = 0
and m.Date <= t.Date
Group by t.title, t.Date
答案 1 :(得分:2)
SELECT ID,
Title,
Date,
Amount,
MTD = SUM(Amount) OVER (PARTITION BY Title, DATEADD(MONTH, DATEDIFF(MONTH, 0, [Date]), 0)),
YTD = SUM(Amount) OVER (PARTITION BY Title, DATEADD(YEAR, DATEDIFF(YEAR, 0, [Date]), 0))
FROM [a_table]
答案 2 :(得分:0)
接受的解决方案不正确。假设我们有一个下表:
ID Title Date Amount
--- ------ ---------- ------
1 Cust A 2020-01-01 2.00
2 Cust A 2020-01-05 3.00
3 Cust A 2020-02-01 5.00
接受的答案会给我们这些结果:
Title Date YTD MTD
------ ---------- ----- -----
Cust A 2021-01-01 2.00 2.00
Cust A 2021-01-05 10.00 10.00
Cust A 2021-02-01 10.00 15.00
这是因为每个连接都将记录数乘以匹配记录数。移除聚合后可以很容易地看到这一点:
Select t.title, t.Date, y.Date, m.Date,
y.Amount,
m.Amount
From [table] t
join [table] y
on y.Title = t.Title
and datediff(year, y.Date, t.Date) = 0
and y.Date <= t.Date
join [table] m
on m.Title = t.Title
and datediff(month, m.Date, t.Date) = 0
and m.Date <= t.Date
Order by t.title, t.Date, y.Date, m.Date
结果:
Title t.Date y.Date m.Date y.Amount m.Amount
----- ---------- ---------- ---------- -------- --------
Cust A 2021-01-01 2021-01-01 2021-01-01 2 2
Cust A 2021-01-05 2021-01-01 2021-01-01 2 2
Cust A 2021-01-05 2021-01-01 2021-01-05 2 3
Cust A 2021-01-05 2021-01-05 2021-01-01 3 2
Cust A 2021-01-05 2021-01-05 2021-01-05 3 3
Cust A 2021-02-01 2021-01-01 2021-02-01 2 5
Cust A 2021-02-01 2021-01-05 2021-02-01 3 5
Cust A 2021-02-01 2021-02-01 2021-02-01 5 5
这是一个产生正确结果的修改后的选择:
Select a.title, a.Date,
Sum(Case When datediff(year, b.Date, a.Date) = 0 Then b.Amount Else 0 End) YTD,
Sum(Case When datediff(month, b.Date, a.Date) = 0 Then b.Amount Else 0 End) MTD
From [table] a
join [table] b
on a.Title = b.Title
and b.Date <= a.Date
Group by a.title, a.Date
结果:
Title Date YTD MTD
------ ---------- ----- -----
Cust A 2021-01-01 2.00 2.00
Cust A 2021-01-05 5.00 5.00
Cust A 2021-02-01 10.00 5.00
这是一个 SQL Fiddle,包含所有当前的答案以及新的解决方案。