我在表格中有记录,其中包含特定级别的代码和附加到该级别的金额。他们没有加起来,这不是问题。
我希望创建一个查询,按级别代码加上它下面级别的值来汇总所有值。我也想在同一查询中每个级别的金额,但没有必要。我在下面创建了一个示例表和输出。有没有人有这样做的好方法?此外,是否有这种卷起的实际定义?
CREATE TABLE LEVEL_AMOUNTS(
LEVEL_CODE char(1)
AMOUNT integer
)
INSERT INTO LEVEL_AMOUNTS VALUES
('A',1),('A',1),('A',1),('A',1),
('B',1),('B',1),('B',1),('B',1),
('C',1),('C',1),('C',1),('C',1)
输出:
A | 12
B | 8
C | 4
答案 0 :(得分:0)
SQL Server 2008没有累积总和。您可以使用子查询或联接来执行此操作:
with cte as (
select level_code, sum(amount) as amount
from amounts
group by level_code
)
select level_code,
(select sum(amount) from cte cte2 where cte.level_code <= cte2.level_code) as cumamount
from cte;
答案 1 :(得分:0)
with cte as (
select distinct level_code
from level_amounts
)
select l.level_code, sum(l.amount)
from cte
inner join level_amounts l on l.level_code <= cte.level_code
group by l.level_code
或
select l.level_code, sum(l.amount)
from level_amounts l
inner join (select distinct level_code
from level_amounts) l1
on l.level_code <= l1.level_code
group by l.level_code;