2013-07-21 3 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

_for에는 하나의 그룹 만있는 _ - 모든 이름은 고유하므로 모든 그룹이 하나만 있습니다. – 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

그 그룹 카운트가 1보다 크지 않은 이름은 그 이름을 유지하지 않는다. (예 : 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