SQL Server中的列明智总计

时间:2019-06-25 06:07:35

标签: sql sql-server tsql

+---------+-------------+-------------+------------+----------+
|  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        |
+---------+-------------+-------------+------------+----------+

我希望显示累积列中的ConsumptionPercent之和。

2 个答案:

答案 0 :(得分:3)

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

SELECT [Item]
   ,[Consumption]
   ,[ConsumptionPercent]
   ,SUM([ConsumptionPercent]) OVER (ORDER BY ([Item]) ROWS UNBOUNDED PRECEDING) AS [Cumulative]
   ,[Category]
FROM YourTable

答案 1 :(得分:0)

尝试使用窗口函数SUM

进行以下查询
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