gpt4 book ai didi

SQL MTD 和 YTD 总和

转载 作者:行者123 更新时间:2023-12-03 00:12:12 26 4
gpt4 key购买 nike

我才刚刚开始研究 SQL。

我有一个 SQL Server 2008 r2 数据库,它将返回两个字段 DocDate 和 InvValue。我需要将 InvValues 求和为截至今天日期的 MTD 和 YTD,所以它看起来像

**Period** ///////  **Total value**
MTD ////////////111111.11
YTD /////////////999999.99

我已经进行了大量的谷歌搜索,并且可以使用 SUM 和 DATEPART 执行其中之一,但我坚持尝试同时执行这两项操作。

有人可以给我一些伪代码来帮助我进一步搜索。

谢谢@Gordon Linoff,这很有帮助,我学到了一些东西,我将来会发现有用的。我的代码现在看起来像:

SELECT
SUM(CASE WHEN YEAR(T1.[DocDate]) = YEAR(GETDATE()) THEN T0.[TotalSumSy] END) AS YTD,
SUM(CASE WHEN YEAR(T1.[DocDate]) = YEAR(GETDATE()) AND MONTH(T1.[DocDate]) = MONTH(GETDATE()) THEN T0.[TotalSumSy] END) AS MTD

FROM [dbo].[INV1] T0 INNER JOIN [dbo].[OINV] T1 ON T1.[DocEntry] = T0.[DocEntry]

但是我现在得到了

YTD.........MTD
99999.99....111111.11

我需要

YTD........99999.99
MTD........11111.11

如有任何进一步的帮助,我们将不胜感激。

最佳答案

您可以通过条件聚合来做到这一点:

select sum(case when year(docdate) = year(getdate()) then InvValue end) as YTD,
sum(case when year(docdate) = year(getdate()) and month(docdate) = month(getdaate())
then InvValue
end) as MTD
from table t;

这假设表中没有 future 日期。如果这样做,请添加 docdate < getdate()这两个条款。

编辑:

如果您需要将其分成两行,您可以简单地执行以下操作:

select (case when n.n = 1 then 'YTD' else 'MTD' end) as which,
(case when n.n = 1 then YTD else MTD end) as value
from (select sum(case when year(docdate) = year(getdate()) then InvValue end) as YTD,
sum(case when year(docdate) = year(getdate()) and month(docdate) = month(getdaate())
then InvValue
end) as MTD
from table t
) cross join
(select 1 as n union all select 2) n;

关于SQL MTD 和 YTD 总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21786302/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com