简体   繁体   English

SQL枢轴和总计?

[英]SQL Pivot and Grand total?

I have a pivot table and I would like to know how to add an extra row that will be the grand total, for example, 我有一个数据透视表,我想知道如何添加一个将成为总计的额外行,例如,

       Christmas,  Hallowen
       500      ,   800
       600      ,   700
Total  1100     ,   1500

Anything like this would help a lot, below is the code I've used to create my pivot table. 像这样的任何事情都会有很大帮助,下面是我用来创建数据透视表的代码。

/*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

The Line below does give the running cost per Party but it would be good to have it as a new row and not as a column, looks a lot better. 下面的行确实给出了每个方的运行成本,但是最好将其作为新行而不是一列,看起来要好得多。

 ,0  + SUM(Phase2.Cost) OVER (ORDER BY [REF]) AS 'Running Total'

Currently my results with the current pivot above are: 目前,我对上面当前要点的结果是:

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

If anyone needs me to clarify something, I'm here. 如果有人需要我澄清一些事情,我在这里。 Hope there's enough information for you all to understand what I'm trying to do. 希望有足够的信息供大家理解我正在尝试做的事情。

Does this do what you want? 这是您想要的吗?

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), () );

This will include an overall total row in the result set. 这将在结果集中包括总的总计行。

If you want running totals, you can include a separate column for each party (one column doesn't make sense with a total row): 如果您希望获得总计,则可以为每一方包括一个单独的列(一列对于合计行没有意义):

SUM(SUM(CASE WHEN Parties = 'Christmas' THEN s.cost ELSE 0 END)) OVER (ORDER BY s.ref) as Christmas,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM