如何按不同名称的列对数据进行求和

时间:2015-11-03 11:52:52

标签: sql sql-server-2008 tsql sql-server-2008-r2

像这样查询:

select [name],count(*) as [count], SUM(balance1) balance1,SUM(balance2) balance2
from mytbl
WHERE [date] between ... --some filters
GROUP BY [name]

查询结果是:

已编辑:

name   balance1    balance2  count
A1      10.00       12.00     10
A2      11.00       20.00     20
A3      9.00        5.00      30
BB1     5.00        2.00      45
BB2     1.00        0.00      50
CCC1    15.00       20.00     23

想要通过字母组成的组必须是:

name   balance1    balance2   count
A1      10.00       12.00      10
A2      11.00       20.00      20
A3      9.00        5.00       30
SUM     30.00       37.00      60
BB1     5.00        2.00       45
BB2     1.00        0.00       50
SUM     6.00        2.00       95
CCC1    15.00       20.00      23
SUM     15.00       20.00      23

已编辑: 示例数据:http://sqlfiddle.com/#!3/977f5/1

怎么做?

1 个答案:

答案 0 :(得分:4)

您可以使用grouping sets

执行此操作
select coalesce(name, 'SUM') as name,
       count(*) as [count],
       SUM(balance1) as balance1, SUM(balance2) as balance2
from mytbl
where [date] between ... --some filters
group by grouping sets( (name, left(name, 1)), (left(name, 1)) );

(注意:这使用coalesce()的懒惰短手来识别" SUM"行。)