【问题标题】:SQL calculate MTD out of YTDSQL 从 YTD 中计算出 MTD
【发布时间】:2022-06-21 16:20:56
【问题描述】:

我尝试在 SQL MTD 中计算表的成本。

我有下表:

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

我现在需要的是每年、用户和类型的 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

我可以用 SQL 中的查询来做到这一点吗?

我试过这样但它不起作用:

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)

【问题讨论】:

  • 您使用的是哪个 DBMS?我已经发布了一个标准的 SQL 答案,它应该适用于大多数 RDBMS,但建议(实际上相当需要)用它们所引用的 MBS 标记 SQL 请求。

标签: sql


【解决方案1】:

您可以使用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;

【讨论】:

  • 完美。非常感谢 :D 解决了我的问题。我只需要调整一件小事。在 ...over(partition by user .... 类型丢失。这里调整后的代码完美运行:cost-COALESCE (lag(cost) OVER (partition BY user, type ORDER BY year, type, month), 0) AS costmtd
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-27
  • 2011-11-04
  • 1970-01-01
  • 1970-01-01
  • 2021-01-16
相关资源
最近更新 更多