简体   繁体   中英

How to write SQL query for following scenario

I have a table in following structure.

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

Now, I want to query all Groups that has only Owner and do not have a single member.

The required query should return the groups G2 and G3 for above table since it has only owners and not a single member.

Can anyone help me to achieve this?

You can do this with aggregation and having :

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

This says that the minimum and maximum value of type is 'Owner' -- which means that the value is always 'Owner' (or possibly NULL ).

Alternatively, you can express the having clause as:

having sum(case when type = 'Member' then 1 else 0 end) = 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

Using Left Outer Join:

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;
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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM