季度累计

时间:2017-02-16 14:31:32

标签: sql sql-server-2008

我目前有一个查询,它会为每个季度生成数据,我想要的总数是一个运行总计。因此,第二季度的数据将被添加到第1季度,依此类推,直到财政年度结束,然后该流程将重新开始。

select  datepart(year,date) as Year,
    CASE
    WHEN MONTH(date) BETWEEN 1  AND 3  THEN convert(char(4), YEAR(date) - 1) + 'Q4'
    WHEN MONTH(date) BETWEEN 4  AND 6  THEN convert(char(4), YEAR(date) - 0) + 'Q1'
    WHEN MONTH(date) BETWEEN 7  AND 9  THEN convert(char(4), YEAR(date) - 0) + 'Q2'
    WHEN MONTH(date) BETWEEN 10 AND 12 THEN convert(char(4), YEAR(date) - 0) + 'Q3'
END AS Quarter,

 Data1,
 Data2,

FROM TABLE

GROUP BY datepart(year,date),
    CASE
    WHEN MONTH(date) BETWEEN 1  AND 3  THEN convert(char(4), YEAR(date) - 1) + 'Q4'
    WHEN MONTH(date) BETWEEN 4  AND 6  THEN convert(char(4), YEAR(date) - 0) + 'Q1'
    WHEN MONTH(date) BETWEEN 7  AND 9  THEN convert(char(4), YEAR(date) - 0) + 'Q2'
    WHEN MONTH(date) BETWEEN 10 AND 12 THEN convert(char(4), YEAR(date) - 0) + 'Q3'
END  

这是我目前得到的

year    quarter     data1        data2

2016      Q1         10            4
2016      Q2         5             6
2016      Q3         4             2
2017      Q4         1             1

我希望输出看起来像这样

year    quarter     data1        data2

2016      Q1         10            4
2016      Q2         15            10
2016      Q3         19            12
2017      Q4         20            13

感谢您的帮助

2 个答案:

答案 0 :(得分:0)

您可以将查询包装在CTE中并使用[ilink32 Error] Error: Unresolved external 'Framestand::TFrameInfo__1 * __fastcall Framestand::TFrameStand::New(Fmx::Types::TFmxObject * const, System::UnicodeString)' referenced from UNIT1.OBJ [ilink32 Error] Error: Unresolved external '__fastcall Framestand::TFrameInfo__1::Show(System::DelphiInterface *> >, System::DelphiInterface *> >, const bool)' referenced from UNIT1.OBJ 来计算累积总和:

CROSS APPLY

答案 1 :(得分:0)

首先,您的查询可以简化为:

SELECT datepart(year, date) as Year,
       datename(year, date) + 'Q' + datename(quarter, dateadd(month, -3, date)) as quarter,
       SUM(Data1) as Data1, SUM(Data2) as Data2
FROM TABLE
GROUP BY datepart(year, date) as Year,
         datename(year, date) + 'Q' + datename(quarter, dateadd(month, -3, date)) as quarter
ORDER BY quarter;

请注意datename()的使用。这将返回一个字符串而不是一个数字,这对于字符串连接更容易。此外,这简化了逻辑,只需减去3个月即可获得该季度。

在SQL Server 2012+中,您可以使用累积总和的内置功能。在SQL Server 2008中,一种方法使用apply

WITH t as (
      SELECT datepart(year, date) as Year,
             datename(year, date) + 'Q' + datename(quarter, dateadd(month, -3, date)) as quarter,
             SUM(Data1) as Data1, SUM(Data2) as Data2
      FROM TABLE
      GROUP BY datepart(year, date) as Year,
               datename(year, date) + 'Q' + datename(quarter, dateadd(month, -3, date)) as quarter
     )
SELECT t.*, tt.data2
FROM t OUTER APPLY
     (SELECT SUM(data1) as data2
      FROM t t2
      WHERE t2.quarter <= t.quarter
     ) tt;