假设我有一个订阅表:
uid | subscription_type
------------------------
Alex | type1
Alex | type2
Alex | type3
Alex | type4
Ben | type2
Ben | type3
Ben | type4
并且只想选择订阅次数超过2但从未订阅过类型1的用户
预期的结果是选择" Ben"仅
我很容易找到使用以下订阅的用户:
SELECT uid
FROM subscribes
GROUP BY uid
HAVING COUNT(*) > 2
但是如何检查组中某些值是否永远不存在?
感谢您的帮助!
答案 0 :(得分:16)
尝试此查询:
SELECT uid
FROM subscribes
GROUP BY uid
HAVING COUNT(*) > 2
AND max( CASE "subscription_type" WHEN 'type1' THEN 1 ELSE 0 END ) = 0
答案 1 :(得分:2)
要检查某些内容是否不存在,请使用[[]]
:
dat[1] = 5
答案 2 :(得分:0)
创建样本表:
CREATE TABLE subscribes
(
uid NVARCHAR(MAX),
subscription_type NVARCHAR(MAX)
)
插入值:
INSERT INTO subscribes
VALUES ('Alex', 'type1'), ('Alex', 'type2'), ('Alex', 'type3'), ('Alex', 'type4'), ('Ben', 'type2'), ('Ben', 'type3'), ('Ben', 'type4')
SQL查询:
SELECT uid
FROM subscribes
GROUP BY uid
HAVING COUNT(*) > 2
AND MAX(CASE subscription_type WHEN 'type1' THEN 1 ELSE 0 END) = 0
输出:
======
|uid |
------
|Ben |
======