我有一个数据透视表,我想知道如何添加一个额外的行,例如,总计,
Christmas, Hallowen
500 , 800
600 , 700
Total 1100 , 1500
任何类似的事情都会有很大帮助,下面是我用来创建数据透视表的代码。
/*Pivot table */
SELECT * FROM
(SELECT Phase2.[Ref]
,Phase2.[Parties]
,Phase2.[TypeOfParty]
,Phase2.[Cost]
,Phase2.[DressCode]
,0 + SUM(Phase2.Cost) OVER (ORDER BY [REF]) AS 'Running Total'
FROM Stage2) AS BaseData
PIVOT(
SUM(BaseData.[Cost])
FOR BaseData.[Parties]
IN([Christmas], [Halloween])
) AS PivotTable
下面的行确实给出了每个方的运行成本,但是最好将其作为新行而不是一列,看起来要好得多。
,0 + SUM(Phase2.Cost) OVER (ORDER BY [REF]) AS 'Running Total'
目前,根据上面的当前数据点,我的结果是:
ref TypeOfParty, DressCode Christmas, Halloween, Running Total
1 Christmas, XmasWear, 500 , 500
2 christmas, XmasWear, 500 , , 1000
3 Halloween, HallWear, , 400 , 400
4 Halloween, HallWear, , 300 , 700
如果有人需要我澄清一些事情,我在这里。希望有足够的信息供大家理解我正在尝试做的事情。
答案 0 :(得分:0)
这是您想要的吗?
SELECT s.Ref, s.TypeOfParty, s.DressCode,
SUM(CASE WHEN Parties = 'Christmas' THEN s.cost ELSE 0 END) as Christmas,
SUM(CASE WHEN Parties = 'Halloween' THEN s.cost ELSE 0 END) as Halloween
FROM Stage2 s
GROUP BY GROUPING SETS ( (s.ref), () );
这将在结果集中包括总的总计行。
如果您想获得总计,则可以为每一方包括一个单独的列(一列对于合计行没有意义):
SUM(SUM(CASE WHEN Parties = 'Christmas' THEN s.cost ELSE 0 END)) OVER (ORDER BY s.ref) as Christmas,