2013-07-21 109 views
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) 

enter image description here複雜的分組問題

首先,我想餘額的總和每個組中,那麼對於只有一組名稱,該名稱應被保留,然後屬於名同一組的名稱也應該更改組名稱。

name | balance 
1   30 
2   9 
white  10 
black  10 
+0

看來這是一個爲我而設的問題! –

+0

這些圖像沒有用處,它們只是重複你在'insert'語句中顯示的內容。你能不能展示你想要輸出的樣子?我無法通過更改名稱來弄清楚你的意思。 – Barmar

+0

_對於只有一個group_的名稱 - 您的所有名稱都是唯一的,因此它們都只有一個組。 – Barmar

回答

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()通常比01更高效。

+0

絕對是最好的方式去做這件事 - http://sqlfiddle.com/#!2/c986f/9 –

+0

絕對是最好的方法 – froodo

0

使用組功能將名稱與每個名稱的餘額總和進行分組。

做到這一點如下:

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

Example

+0

非常感謝...代碼是好的 – froodo

+0

它的工作很好,除了名稱的組數不超過一個名稱不保留他們的名字(即3應該是白色的,4應該是黑色的) – froodo

+0

任何運氣?..只是編輯該問題顯示預期的結果....謝謝。 – froodo

0
select case count(distinct name) 
     when 1 then name 
     else thegroup 
     end as name, 
     sum(balance) as balance 
from theRecords 
group by thegroup 
+0

select case count(*) when 1 then name else thegroup end as name, sum(balance) as balance from theRecords group by thegroup,name froodo

+0

不,它應該只是由羣組分組,因爲這就是你如何計算名稱的數目 – Barmar

+0

我改變了count(*)到count(不同的名稱)',因爲我認爲可以有重複的名稱,我們不應該分開計數它們。 – Barmar