我有一个具有唯一KEY(UserID和Type)
的表UserID | Type | Column1 | Column2
----------------------------
1 | 1 | *NULL* | 1
1 | 2 | ABC | *NULL*
1 | 3 | *NULL* | 2
2 | 1 | *NULL* | 1
2 | 2 | CDE | *NULL*
3 | 1 | *NULL* | 3
3 | 2 | DTE | *NULL*
我正在尝试构建查询以搜索所有用户ID包含:
(Type=1 AND Column2=1) AND (Type=3 AND Column2=2)
答案 0 :(得分:1)
这个问题与递归CTE无关。您可以使用聚合和having
子句来解决它:
select userid
from t
where (Type = 1 AND Column2 = 1) OR (Type = 3 AND Column2 = 2)
group by userid
having count(distinct type) = 2;
答案 1 :(得分:0)
With CTE(userid)
AS
(
SELECT userid
FROM t
WHERE (Type = 1 AND Column2 = 1)
)
SELECT userid
FROM CTE
WHERE EXISTS(
SELECT 1
FROM CTE
WHERE Type = 3 AND Column2 = 2 )