2012-04-26 49 views
1

我有如下表使用情況與條款

ID TYPE  
--- ----  
1  P  
1  W  
2  P  
3  W  
4  W  
4  X  
5  P  
6  null 

我需要一個新的表,選擇與組聚合函數像下面

ID Count of Type  Code  
-- --------------  -------  
1  2    null  
2  1    P  
3  1    W  
4  2    null  
5  1    P  
6  0    null  


1st col ---> ID  
2nd col ---> count of "type" for an ID  
3rd col ---> if count(type) = 1 then TYPE  
      else null  

請幫我在一個創建寫一個ORACLE SQL查詢

回答

3

你可以使用子查詢與max函數來得到該代碼的值,然後使用一個case語句來獲得最終的查詢只計數時= 1的值。

select id, cnt, case when cnt=1 then maxtype else null end as code 
from 
(select id, count(*) as cnt, max(type) as maxtype 
from t1 
group by id) t2