季度销售额总和

时间:2016-04-07 16:15:58

标签: sql sql-server sum

我如何使用SQL和SUM月度数据(季度视图)?我不会使用存储过程等。

Current data:
   ID  |  Sales
201601 |   5
201602 |   15
201603 |   5
201604 |   20
201605 |   8
201606 |   2

...

我的ID栏就像yyyymm

我想要的是:

Quarter  |  Sales
   Q1    |   25
   Q2    |   30

....

2 个答案:

答案 0 :(得分:0)

您可以尝试下面的查询

SELECT 
  LEFT(ID,4) Year,
  'Q'+ CAST((CAST(RIGHT(ID,2) AS INT)-1 )/3 +1 AS varchar) Quarter,
  SUM(Sales) Sales
FROM 
   Yourtable
GROUP BY 
  LEFT(ID,4), 
  'Q'+ CAST((CAST(RIGHT(ID,2) AS INT) -1 )/3 +1 AS varchar) 
order by year

<强> SQL demo link

答案 1 :(得分:0)

您可以使用DATEPARTQUARTER获取DATETIME的四分之一。您只需使用DATETIME构建DATEFROMPARTS并解析您的ID列。

CONCAT只是添加了Q&#39; Q&#39;至期间数。

SELECT  LEFT(id,4) [Year], 
        CONCAT('Q',DATEPART(QUARTER, DATEFROMPARTS(LEFT(id,4), RIGHT(id, 2), 1))) [Quarter],
        SUM(Sales) [Sales]
FROM    yourtable
GROUP BY LEFT(id,4), DATEPART(q, DATEFROMPARTS(LEFT(id,4), RIGHT(id, 2), 1))
ORDER BY [Year], [Quarter]