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

后端 未结 3 1967
慢半拍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 |
    ======
    
    0 讨论(0)
  • 2020-12-28 09:15

    To check if something doesn't exist, use NOT EXISTS(...):

    SELECT uid
    FROM subscribes su
    WHERE NOT EXISTS (SELECT *
            FROM subscribes nx
            WHERE nx.uid = su.uid AND nx.subscription_type = 'type1'
            )
    GROUP BY uid HAVING COUNT(*) > 2
            ;
    
    0 讨论(0)
  • 2020-12-28 09:17

    Try this query:

    SELECT uid 
    FROM subscribes 
    GROUP BY uid 
    HAVING COUNT(*) > 2
       AND max( CASE "subscription_type"  WHEN 'type1' THEN 1 ELSE 0 END ) = 0
    
    0 讨论(0)
提交回复
热议问题