How to check if value exists in each group (after group by)

后端 未结 3 1969
慢半拍i
慢半拍i 2020-12-28 08:39

Assume I have a subscriptions table :

uid  | subscription_type 
------------------------  
Alex | type1
Alex | type2
Alex | type3
Alex | type4
Ben  | type2
B         


        
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-28 09:06

    Create Sample Table:

    CREATE TABLE subscribes
    (
    uid NVARCHAR(MAX),
    subscription_type NVARCHAR(MAX)
    )
    

    Insert Values:

    INSERT INTO subscribes
    VALUES ('Alex', 'type1'), ('Alex', 'type2'), ('Alex', 'type3'), ('Alex', 'type4'),  ('Ben', 'type2'), ('Ben', 'type3'), ('Ben', 'type4')
    

    SQL Query:

    SELECT uid
    FROM subscribes
    GROUP BY uid
    HAVING COUNT(*) > 2
    AND MAX(CASE subscription_type WHEN 'type1' THEN 1 ELSE 0 END) = 0
    

    Output:

    ======
    |uid |
    ------
    |Ben |
    ======
    

提交回复
热议问题