将总计行添加到数据透视表的底部

Add A Total Row To Bottom Of Pivot

我看到使用 GROUP BY CUBE() 会在数据透视表的底部添加一个总计行,我一直在努力使我的语法准确无误,以便我可以这样做。好吧,我有我的语法 运行,但我没有在结果集的底部得到总计。这是为什么?

select *
FROM
(
  select case 
  WHEN a.state LIKE 'CA' THEN 'California'
  WHEN a.state LIKE 'WA' THEN 'Washington'
  else a.state
  end As [Full State], 
  SaleID As [Sales By State], 
  CONVERT(VARCHAR(20), dt.CumulativeWeek) AS Week
  FROM retailsales.Store1 a
  INNER JOIN retailsales.customCalendar dt
  ON a.orderDate = dt.orderDate
  WHERE a.orderDate IS NOT NULL
  GROUP BY CUBE (SaleID, state, dt.CumulativeWeek)
) src
pivot
(
  COUNT([Sales By State])
  For Week IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13])
) piv

我尝试将 CUBE() 语句移到我的数据透视表之外,但在此处遇到编译错误是更新的代码

select *
FROM
(
  select case 
  WHEN a.state LIKE 'CA' THEN 'California'
  WHEN a.state LIKE 'WA' THEN 'Washington'
  else a.state
  end As [Full State], 
  SaleID As [Sales By State], 
  CONVERT(VARCHAR(20), dt.CumulativeWeek) AS Week
  FROM retailsales.Store1 a
  INNER JOIN retailsales.customCalendar dt
  ON a.orderDate = dt.orderDate
  WHERE a.orderDate IS NOT NULL
  GROUP BY CUBE (SaleID, state, dt.CumulativeWeek)
) src
pivot
(
  COUNT([Sales By State])
  For Week IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13])
) piv
GROUP BY CUBE (Full State)

这会产生此编译错误

Msg 8120, Level 16, State 1, Line 1
Column 'piv.1' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

带有聚合行的 UNION ALL 将向您显示带有 SUM 的原始旋转数据

WITH data AS (
    select *
    FROM
    (
      select case 
      WHEN a.state LIKE 'CA' THEN 'California'
      WHEN a.state LIKE 'WA' THEN 'Washington'
      else a.state
      end As [Full State], 
      SaleID As [Sales By State], 
      CONVERT(VARCHAR(20), dt.CumulativeWeek) AS Week
      FROM retailsales.Store1 a
      INNER JOIN retailsales.customCalendar dt
      ON a.orderDate = dt.orderDate
      WHERE a.orderDate IS NOT NULL
      GROUP BY CUBE (SaleID, state, dt.CumulativeWeek)
    ) src
    pivot
    (
      COUNT([Sales By State])
      For Week IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13])
    ) piv
)
SELECT [Full State]
     , [1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13]
FROM   data
UNION ALL
SELECT ''
     , SUM([1]),SUM([2]),SUM([3]),SUM([4]),SUM([5]),SUM([6])
     , SUM([7]),SUM([8]),SUM([9]),SUM([10]),SUM([11]),SUM([12]),SUM([13])
FROM   data