Sum pivoted columns

时间:2012-08-16 20:13:20

标签: asp.net sql pivot

我有这个带有透视数据的gridview:

    Store        MEX       USA
    Supermarket  10,000    5,000
    Club         10,000        0
    Direct        4,000    1,000

完成此查询:

    SELECT * 
    FROM [Sales] 
    PIVOT ( 
            SUM(Sales) 
            FOR Region IN ( [MEX], [USA] ) 
    ) AS SalesPerRegion

现在我想在页脚上添加MEX和USA的销售总额,我不知道该怎么做。

感谢任何帮助,谢谢!

1 个答案:

答案 0 :(得分:1)

您可以添加UNION ALL以获得每个地区的总计SUM()

SELECT Store, MEX, USA 
FROM [Sales] 
PIVOT ( 
        SUM(Sales) 
        FOR Region IN ( [MEX], [USA] ) 
) AS SalesPerRegion

UNION ALL

SELECT 'Total', Sum(MEX), Sum(USA)
FROM
(
    SELECT Store, MEX, USA 
    FROM [Sales] 
    PIVOT ( 
           SUM(Sales) 
           FOR Region IN ( [MEX], [USA] ) 
    ) AS SalesPerRegion
) x

请参阅SQL Fiddle with Demo