SQL:列总和

SQL: Column Sum

让我们有以下示例 table:

Person Quantity
A      1
B      2
C      3
D      4
E      5

结果应该是:

PersonAggregate
1     (0+Quantity of PersonA)=sumA
3     (sumA+Quantity of PersonB)=sumB
6     (sumB+Quantity of PersonC)=sumC
10    (sumC+Quantity of PersonD)=sumD
15    (sumD+Quantity of PersonE)

onq SQL-query 是否可以得到这个结果?

这显然会得到个人的总和。

select person, sum(quantity)
from sample
group by person
order by person

我不认为你想要的效果可以通过基于集合的方式来完成。带有游标的程序语言,如 T-SQL 或 PLSQL,可以轻松做到。

我会写一个存储过程并调用它。

SQL 的大多数版本都支持累加和作为 window 函数:

select person, sum(quantity) over (order by person) as cumesum
from sample;

您也可以使用相关子查询来做到这一点:

select s.person,
       (select sum(s2.quantity)
        from samples s2
        where s2.person <= s.person
       ) as cumesum
from sample s;

如果 sample table 每人超过一行且需要求和多个数量,您可以使用:

select curr.person, curr.sum_person + case when prev.person <> curr.person
                                           then prev.sum_person
                                           else 0 end as person_sum
  from (select person, sum(quantity) as sum_person
          from sample
         group by person) curr
 cross join (select person, sum(quantity) as sum_person
               from sample
              group by person) prev
 where prev.person =
       (select max(x.person) from sample x where x.person < curr.person)
    or curr.person = (select min(person) from sample)
 group by curr.person

Fiddle: http://sqlfiddle.com/#!2/7c3135/6/0

输出:

| PERSON | PERSON_SUM |
|--------|------------|
|      A |          1 |
|      B |          3 |
|      C |          5 |
|      D |          7 |
|      E |          9 |

如果sampletable每人只有一行,你可以更简单地使用:

select curr.person, curr.quantity +   case when prev.person <> curr.person
                                           then prev.quantity
                                           else 0 end as person_sum
  from sample curr
 cross join sample prev
 where prev.person =
       (select max(x.person) from sample x where x.person < curr.person)
    or curr.person = (select min(person) from sample)
 group by curr.person

Fiddle: http://sqlfiddle.com/#!2/7c3135/8/0

返回的输出是相同的,因为在您的示例中,每个人只有一行。

如果使用 Oracle、SQL Server 或支持分析功能的数据库,您可以使用:

如果sample每人排一排:

select person,
       sum(quantity) over(order by person rows between 1 preceding and current row) as your_sum
  from sample
 order by person

Fiddle: http://sqlfiddle.com/#!4/82e6f/1/0

如果 sample 每人超过 2 行:

select person,
       sum(sum_person) over(order by person rows between 1 preceding and current row) as your_sum
  from (select person, sum(quantity) as sum_person
          from sample
         group by person) x
 order by person

Fiddle: http://sqlfiddle.com/#!4/82e6f/4/0