Add a summary row with totals

后端 未结 5 1441
不知归路
不知归路 2020-11-27 02:55

I know this sounds crazy and probably should not be done this way but I need something like this - I have a records from SELECT [Type], [Total Sales] From Before

相关标签:
5条回答
  • 2020-11-27 03:30

    You could use the ROLLUP operator

    SELECT  CASE 
                WHEN (GROUPING([Type]) = 1) THEN 'Total'
                ELSE [Type] END AS [TYPE]
            ,SUM([Total Sales]) as Total_Sales
    From    Before
    GROUP BY
            [Type] WITH ROLLUP
    
    0 讨论(0)
  • 2020-11-27 03:30

    If you want to display more column values without an aggregation function use GROUPING SETS instead of ROLLUP:

    SELECT
      Type = ISNULL(Type, 'Total'),
      SomeIntColumn = ISNULL(SomeIntColumn, 0),
      TotalSales = SUM(TotalSales)
    FROM atable
    GROUP BY GROUPING SETS ((Type, SomeIntColumn ), ())
    ORDER BY SomeIntColumn --Displays summary row as the first row in query result
    
    0 讨论(0)
  • 2020-11-27 03:44

    This is the more powerful grouping / rollup syntax you'll want to use in SQL Server 2008+. Always useful to specify the version you're using so we don't have to guess.

    SELECT 
      [Type] = COALESCE([Type], 'Total'), 
      [Total Sales] = SUM([Total Sales])
    FROM dbo.Before
    GROUP BY GROUPING SETS(([Type]),());
    

    Craig Freedman wrote a great blog post introducing GROUPING SETS.

    0 讨论(0)
  • 2020-11-27 03:44

    Try to use union all as below

    SELECT [Type], [Total Sales] From Before
    union all
    SELECT 'Total', Sum([Total Sales]) From Before
    

    if you have problem with ordering, as i-one suggested try this:

    select [Type], [Total Sales] 
    from (SELECT [Type], [Total Sales], 0 [Key] 
          From Before 
          union all 
          SELECT 'Total', Sum([Total Sales]), 1 From Before) sq 
    order by [Key], Type
    
    0 讨论(0)
  • 2020-11-27 03:45

    If you are on SQL Server 2008 or later version, you can use the ROLLUP() GROUP BY function:

    SELECT
      Type = ISNULL(Type, 'Total'),
      TotalSales = SUM(TotalSales)
    FROM atable
    GROUP BY ROLLUP(Type)
    ;
    

    This assumes that the Type column cannot have NULLs and so the NULL in this query would indicate the rollup row, the one with the grand total. However, if the Type column can have NULLs of its own, the more proper type of accounting for the total row would be like in @Declan_K's answer, i.e. using the GROUPING() function:

    SELECT
      Type = CASE GROUPING(Type) WHEN 1 THEN 'Total' ELSE Type END,
      TotalSales = SUM(TotalSales)
    FROM atable
    GROUP BY ROLLUP(Type)
    ;
    
    0 讨论(0)
提交回复
热议问题