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)

ここに画像の説明を入力

まず、各グループの残高の合計を取得したい。次に、グループが 1 つしかない名前の場合、名前を保持し、同じグループに属する名前の名前もグループ名に変更する必要があります。

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()max()一般に よりも効率的ですcount(distinct)

于 2013-07-21T11:38:12.250 に答える