Assume I have a subscriptions table :
uid | subscription_type
------------------------
Alex | type1
Alex | type2
Alex | type3
Alex | type4
Ben | type2
B
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 |
======
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
;
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