[英]SQL calculate MTD out of YTD
I try to calculate in SQL MTD cost of a table.我尝试在 SQL MTD 中计算表的成本。
I have following table:我有下表:
year![]() |
user![]() |
month![]() |
type![]() |
cost![]() |
blank![]() |
---|---|---|---|---|---|
2021 ![]() |
a![]() |
1 ![]() |
type1![]() |
10 ![]() |
0 ![]() |
2021 ![]() |
a![]() |
2 ![]() |
type1![]() |
20 ![]() |
0 ![]() |
2021 ![]() |
a![]() |
3 ![]() |
type1![]() |
35 ![]() |
0 ![]() |
2022 ![]() |
a![]() |
1 ![]() |
type1![]() |
5 ![]() |
0 ![]() |
2022 ![]() |
a![]() |
2 ![]() |
type1![]() |
35 ![]() |
0 ![]() |
2021 ![]() |
b ![]() |
1 ![]() |
type1![]() |
10 ![]() |
0 ![]() |
2021 ![]() |
b ![]() |
2 ![]() |
type1![]() |
30 ![]() |
0 ![]() |
What I need to have is now the MTD cost as per year, user and type我现在需要的是每年、用户和类型的 MTD 成本
year![]() |
user![]() |
month![]() |
type![]() |
cost![]() |
costMTD![]() |
blank![]() |
---|---|---|---|---|---|---|
2021 ![]() |
a![]() |
1 ![]() |
type1![]() |
10 ![]() |
10 ![]() |
0 ![]() |
2021 ![]() |
a![]() |
2 ![]() |
type1![]() |
20 ![]() |
10 ![]() |
0 ![]() |
2021 ![]() |
a![]() |
3 ![]() |
type1![]() |
35 ![]() |
15 ![]() |
0 ![]() |
2022 ![]() |
a![]() |
1 ![]() |
type1![]() |
5 ![]() |
5 ![]() |
0 ![]() |
2022 ![]() |
a![]() |
2 ![]() |
type1![]() |
35 ![]() |
30 ![]() |
0 ![]() |
2021 ![]() |
b ![]() |
1 ![]() |
type1![]() |
10 ![]() |
10 ![]() |
0 ![]() |
2021 ![]() |
b ![]() |
2 ![]() |
type1![]() |
30 ![]() |
20 ![]() |
0 ![]() |
Can i do this with a query in SQL?我可以用 SQL 中的查询来做到这一点吗?
I tried like this but it doesn't work:我试过这样但它不起作用:
SELECT t1.year, t1.user, t1.month, t1.type, t1.cost,
iif(t1.month = '1', t1.cost, t1.cost- t2.cost) AS costMTD, 0 AS blank
FROM dbo.usercosts AS t1 INNER JOIN dbo.usercosts AS t2
ON t1.year = t2.year
AND t1.user= t2.user
AND t1.type= t2.type
AND t2.month = iif(t2.month = '1', '1', t1.month - 1)
You can use LAG
to see the previous row's cost.您可以使用
LAG
查看上一行的成本。
select
year, user, month, type, cost,
cost - coalesce(lag(cost) over(partition by user order by year, month), 0) as costmtd,
0 as blank
from dbo.usercosts as
order by user, year, month;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.