在sql的一行中每5行求和一次

时间:2014-11-29 09:49:12

标签: sql sum

我是sql Database.i的新手有问题

我的桌子就像这样

s.no |name  | amount
---------------------
1  | xyz    |   15
2  | xyz    |   54
3  | xyz    |  787
4  | xyz    |  455
5  | hhh    |   58
6  | hhh    |  789
7  | hhh    |  478
8  | hhh    | 7855

我想要这样的结果。

id |name|   | amount
---------------------
1  | xyz    |   15
2  | xyz    |   54
3  | xyz    |  787
4  | xyz    |  455
   | total  | 1311
5  | hhh    |   58
6  | hhh    |  789
7  | hhh    |  478
8  | hhh    | 7855
    total   | 9180

3 个答案:

答案 0 :(得分:1)

看起来你想要许多数据库支持的rollup子句。

以下是MySQL中的查询内容:

select s.no, name, sum(amount)
from mytable
group by name, s.no with rollup

您可以执行coalesce(s.no, 'total')之类的操作来查看字符串总数而不是NULL

答案 1 :(得分:0)

尝试这样

 select id,name,amount,grp from (

 select id,name,amount,name as grp from table1
 union ll
 select 0 as id,'Total' as name,sum(amount) as amount,
 concat(name,'-Total') as grp
 from table1 group by name ) as tab1 order by grp

答案 2 :(得分:0)

如果每5行只需要总数,则可以运行以下代码:

SELECT ceil(rownum/5) as "Group", sum(amount) as "sum_Efive"
FROM s.no
group by ceil(rownum/5);