SQL Server中的按列总计

SQL Server中的按列总计,sql,sql-server,tsql,Sql,Sql Server,Tsql,我希望在“显示累计”列中显示消耗百分比的总和。尝试使用窗口功能进行以下查询sum +---------+-------------+-------------+------------+----------+ | Item | Consumption | %Consumption| %Cumulative| Category | +---------+-------------+-------------+------------+----------+ | Item 1 |

我希望在“显示累计”列中显示消耗百分比的总和。

尝试使用窗口功能进行以下查询
sum

+---------+-------------+-------------+------------+----------+
|  Item   | Consumption | %Consumption| %Cumulative| Category |
+---------+-------------+-------------+------------+----------+
| Item 1  |         500 |       28.17 |      28.17 | A        |
| Item 2  |         450 |       25.35 |      53.52 | A        |
| Item 3  |         350 |       19.72 |      73.24 | A        |
| Item 4  |         200 |       11.27 |      84.51 | B        |
| Item 5  |         150 |        8.45 |      92.96 | B        |
| Item 6  |         100 |        5.63 |      98.59 | B        |
| Item 7  |          10 |        0.56 |      99.15 | C        |
| Item 8  |           4 |        0.23 |      99.38 | C        |
| Item 9  |           2 |        0.11 |      99.49 | C        |
| Item 10 |           6 |        0.34 |      99.83 | C        |
| Item 11 |           3 |        0.17 |     100.00 | C        |
+---------+-------------+-------------+------------+----------+

以下查询应执行您想要的操作:

select Item,
    Consumption,
    ConsumptionPercent,
    sum(ConsumptionPercent) over (order by id),
    Category
from (
    select cast(substring(Item, 6, length(item)) as int) id, *
    from MyTable
) a

嗨,Mjoy,我想最后一行是100%,但它是999.99,这是可能的?我相信最后一行是99.99,而不是999.99,ConsumptionPercent列的数据类型是什么?它的结果不是列这可能会帮助您解决问题
SELECT [Item]
   ,[Consumption]
   ,[ConsumptionPercent]
   ,SUM([ConsumptionPercent]) OVER (ORDER BY ([Item]) ROWS UNBOUNDED PRECEDING) AS [Cumulative]
   ,[Category]
FROM YourTable