查询中的复杂分组问题

时间:2013-07-21 09:52:52

标签: sql sql-server grouping

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)

enter image description here

首先,我希望获得每个组中的余额总和,然后对于只有一个组的名称,应保留名称,然后属于同一组的名称的名称也应更改为组名。 / p>

name  | balance 
1          30
2           9
white      10
black      10

3 个答案:

答案 0 :(得分: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()max()通常比count(distinct)更有效。

答案 1 :(得分:0)

使用组功能将名称与每个名称的余额之和进行分组。

请执行以下操作:

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

Example

答案 2 :(得分:0)

select case count(distinct name)
         when 1 then name
         else thegroup
       end as name,
       sum(balance) as balance
from theRecords
group by thegroup
相关问题