2016-06-18 73 views
1

我在下面的結構中有一個表。如何爲以下方案編寫SQL查詢

Group Member/Owner Type 

G1  M1   Member 
G1  OW1   Owner 
G2  OW1   Owner 
G3  OW1   Owner 
G3  OW2   Owner 
G4  M2   Member 
G4  OW2   Owner 

現在,我想要查詢所有隻有所有者並且沒有單個成員的組。

所需的查詢應該返回組G2和上面的表格G3,因爲它只有業主,而不是一個單一的成員。

任何人都可以幫助我實現這個目標嗎?

回答

3

您可以通過聚集和having做到這一點:

select [group] 
from t 
group by [group] 
having min(type) = 'Owner' and max(type) = 'Owner'; 

這是說的type的最小值和最大值爲'Owner' - 這意味着該值始終'Owner'(或可能NULL)。

或者,你可以表達having子句:

having sum(case when type = 'Member' then 1 else 0 end) = 0 
+0

感謝@Gordon Linoff – kombsh

0
Select [group] from 
    (
Select [group], 
sum(case when type='member' then 1 else 0 end) as cntmember, 
    sum(case when type='owner' then 1 else 0 end) as cntowner 
    from tab group by [group]) tab 
    where cntmember=0 and cntowner=1 
0

使用左外連接:

SELECT G1 FROM 

    (SELECT GROUPS G1, TYPE T1 FROM temp 
    WHERE TYPE = 'Owner') TAB1 
     LEFT JOIN 
    (SELECT GROUPS G2, TYPE T2 FROM temp 
    WHERE TYPE = 'Member') TAB2 
     ON TAB1.G1 = TAB2.G2 

WHERE T2 IS NULL 
GROUP BY G1; 
0
declare @Table1 TABLE 
    (Groups varchar(2), Owner varchar(3), Type varchar(6)) 
; 

INSERT INTO @Table1 
    (Groups, Owner, Type) 
VALUES 
    ('G1', 'M1', 'Member'), 
    ('G1', 'OW1', 'Owner'), 
    ('G2', 'OW1', 'Owner'), 
    ('G3', 'OW1', 'Owner'), 
    ('G3', 'OW2', 'Owner'), 
    ('G4', 'M2', 'Member'), 
    ('G4', 'OW2', 'Owner') 
; 

;WITH CTE AS (
Select T.Groups,T.Type,T.Owner from (
select Groups, Owner, Type,ROW_NUMBER()OVER(PARTITION BY Groups ORDER BY Type)RN from @Table1 
)T WHERE T.RN = 1 AND T.Type <> 'member') 

Select * from @Table1 T WHERE EXISTS (Select 1 from CTE WHERE Groups = T.Groups)