如何为以下场景编写SQL查询

时间:2016-06-18 07:28:44

标签: sql sql-server sql-server-2008

我有一个以下结构的表格。

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 组,因为它只有所有者而不是单个成员。

任何人都可以帮我实现这个目标吗?

4 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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;

答案 3 :(得分: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)