简体   繁体   English

SQL 从 YTD 中计算出 MTD

[英]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 2021 a一个 1 1 type1类型1 10 10 0 0
2021 2021 a一个 2 2 type1类型1 20 20 0 0
2021 2021 a一个 3 3 type1类型1 35 35 0 0
2022 2022 a一个 1 1 type1类型1 5 5 0 0
2022 2022 a一个 2 2 type1类型1 35 35 0 0
2021 2021 b b 1 1 type1类型1 10 10 0 0
2021 2021 b b 2 2 type1类型1 30 30 0 0

What I need to have is now the MTD cost as per year, user and type我现在需要的是每年、用户和类型的 MTD 成本

year user用户 month type类型 cost成本 costMTD成本MTD blank空白的
2021 2021 a一个 1 1 type1类型1 10 10 10 10 0 0
2021 2021 a一个 2 2 type1类型1 20 20 10 10 0 0
2021 2021 a一个 3 3 type1类型1 35 35 15 15 0 0
2022 2022 a一个 1 1 type1类型1 5 5 5 5 0 0
2022 2022 a一个 2 2 type1类型1 35 35 30 30 0 0
2021 2021 b b 1 1 type1类型1 10 10 10 10 0 0
2021 2021 b b 2 2 type1类型1 30 30 20 20 0 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM