1
CREATE TABLE [dbo].[theRecords](
[id] [int] IDENTITY(1,1) NOT NULL,
[name] [varchar](50) NULL,
[thegroup] [varchar](50) NULL,
[balance] [int] NULL,
)


GO

insert into theRecords values('blue',1,10)
insert into theRecords values('green',1,20)
insert into theRecords values('yellow',2,5)
insert into theRecords values('red',2,4)
insert into theRecords values('white',3,10)
insert into theRecords values('black',4,10)

在此处输入图像描述

首先,我想得到每个组的余额总和,然后对于只有一个组的名称,应该保留名称,然后属于同一组的名称也应该更改组名。

name  | balance 
1          30
2           9
white      10
black      10
4

3 回答 3

2

为了确定所有名称是否相同,我喜欢比较最小值和最大值:

select (case when min(name) = max(name) then max(name)
             else thegroup
        end) as name,
       sum(balance) as balance
from theRecords r
group by thegroup;

计算min()andmax()通常比 a 更有效count(distinct)

于 2013-07-21T11:38:12.250 回答
0

使用 group 函数将名称与每个名称的余额总和进行分组。

在下面执行此操作:

select thegroup "name", sum(balance) "balance"
from theRecords group by thegroup order by 1;

例子

于 2013-07-21T10:04:46.847 回答
0
select case count(distinct name)
         when 1 then name
         else thegroup
       end as name,
       sum(balance) as balance
from theRecords
group by thegroup
于 2013-07-21T10:10:43.390 回答