按年和月分组总和

时间:2017-09-21 17:43:53

标签: sql

我在SQL中有一个包含发票数据的表。我关心的唯一两列是金额和日期。我有几千行跨越几年

例如

19.32        2017-01-01 03:28:37.787

我的查询看起来像这样

SELECT * FROM (
  SELECT
    YEAR(CreatedUtc) AS [Year],
    MONTH(CreatedUtc) AS [Month], 
    DATENAME(MONTH, CreatedUtc) AS [Month Name],
    SUM(InvoiceTotal) as [InvoiceTotal]
  FROM [dbo].[Invoice]
  GROUP BY YEAR(CreatedUtc), MONTH(CreatedUtc), DATENAME(MONTH,CreatedUtc)
) AS t

PIVOT (
  SUM(InvoiceTotal) 
  FOR [Month Name] IN ([January],[February],[March],[April],[May],
    [June],[July],[August],[September],[October],[November],
    [December])) AS MNamePivot
ORDER BY 1,2

然而,我的结果很接近,但不完全是我想要的。我如何才能在一条线上每年获得12个月?

Year    Month   January February    March   April   May June    July    August  September   October November    December

2013    10  NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    3803.15 NULL    NULL

2013    11  NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    4039.90 NULL

2013    12  NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    4498.70

2014    1   27139.45    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL

2014    2   NULL    28164.61    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL

2014    3   NULL    NULL    29185.82    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL

2014    4   NULL    NULL    NULL    29933.51    NULL    NULL    NULL    NULL    NULL    NULL    NULL    NULL

2014    5   NULL    NULL    NULL    NULL    30470.01    NULL    NULL    NULL    NULL    NULL    NULL    NULL

2014    6   NULL    NULL    NULL    NULL    NULL    32100.82    NULL    NULL    NULL    NULL    NULL    NULL

1 个答案:

答案 0 :(得分:0)

只需从MONTH(CreatedUtc) AS [Month]SELECT移除GROUP BY,然后单独按进行分组。事实上,按进行分组是多余的,因为您在列中按其进行转换。

SELECT * FROM (
  SELECT
    YEAR(CreatedUtc) AS [Year],
    MONTH(CreatedUtc) AS [Month], 
    DATENAME(MONTH, CreatedUtc) AS [Month Name],
    SUM(InvoiceTotal) as [InvoiceTotal]
  FROM [dbo].[Invoice]
  GROUP BY YEAR(CreatedUtc), DATENAME(MONTH,CreatedUtc)
) AS t

PIVOT (
  SUM(InvoiceTotal) 
  FOR [Month Name] IN ([January],[February],[March],[April],[May],
    [June],[July],[August],[September],[October],[November],
    [December])) AS MNamePivot
ORDER BY 1,2

使用随机数据查看Rextester demo