SQL查询到每个类别的Sum列

时间:2015-01-15 16:07:11

标签: sql sql-server sql-server-2008-r2 report

enter image description here请附上我想要生成的表格。查询的输出返回“现有表”中指定的数据。我试图在必需表中生成表。到目前为止,没有任何成功。如图所示,为每个州和城市添加了列。

知道怎么做到这一点吗?我正在使用SQL Server 2008 R2。

感谢帮助。

2 个答案:

答案 0 :(得分:1)

您可以将SUM聚合函数与OVER子句一起使用,如http://msdn.microsoft.com/en-us/library/ms187810(v=sql.105).aspx

中所述

根据上面的页面,以下代码应与您的查询兼容:

SELECT 
    [State], 
    City, 
    Item, 
    Cost, 
    Tax, 
    SUM(Cost) OVER (PARTITION BY [State], City) AS CumulativeCost, 
    SUM(Tax) OVER (PARTITION BY [State], City) AS CumulativeTax
FROM -- Replace the below with your table
(
    SELECT 'A' AS [State], 'AC' AS [City], 'Item1' AS [Item], 10 AS [Cost], 1 AS Tax UNION
    SELECT 'A' AS [State], 'AC' AS [City], 'Item2' AS [Item], 30 AS [Cost], 2 AS Tax UNION
    SELECT 'B' AS [State], 'BC' AS [City], 'Item1' AS [Item], 40 AS [Cost], 1 AS Tax UNION
    SELECT 'B' AS [State], 'BC' AS [City], 'Item2' AS [Item], 10 AS [Cost], 1 AS Tax
) t

答案 1 :(得分:0)

ROLLUP做了这个伎俩。这是我提到的链接。

http://technet.microsoft.com/en-us/library/ms189305%28v=sql.90%29.aspx