以下是我的数据。
with cte as(
select 'A' name, 0 status
union all select 'A' name, 1 status
union all select 'B' name, 1 status
union all select 'C' name, 2 status
union all select 'D' name, 1 status
)
我希望只获得B, C, D
作为查询的输出。可以说,0
是status-complete
&我想忽略与之相关的记录。
我可以使用下面的not in
子句来实现。
select * from cte c
where c.name not in (select cf.name from cte cf where cf.status=0)
但我希望在exists
条件下使用not exists
或where
子句实现此目的。
请你分享逻辑吗?
感谢,
答案 0 :(得分:1)
请你试试这个:
SELECT * FROM cte c
WHERE NOT EXISTS (SELECT cf.name
FROM cte cf WHERE c.name = cf.name AND cf.status = 0)
为此,我们不需要where子句中的任何列,因为我们将该条件列作为子查询的WHERE中的比较来寻址。
答案 1 :(得分:1)
使用 NOT EXISTS
with cte as(
select 'A' name, 0 status
union all select 'A' name, 1 status
union all select 'B' name, 1 status
union all select 'C' name, 2 status
union all select 'D' name, 1 status
)
select * from cte out where NOT EXISTS
(select inn.name from cte inn WHERE out.name = inn.name and inn.status=0)
答案 2 :(得分:1)
DECLARE @tbl1 AS TABLE
(
Name VARCHAR(50),
Status INT
)
INSERT INTO @tbl1 VALUES('A',0)
INSERT INTO @tbl1 VALUES('A',1)
INSERT INTO @tbl1 VALUES('B',1)
INSERT INTO @tbl1 VALUES('C',1)
INSERT INTO @tbl1 VALUES('D',1)
INSERT INTO @tbl1 VALUES('E',0)
使用不是EXISTS:
SELECT
*
FROM @tbl1 T1
WHERE NOT EXISTS( SELECT T2.Name FROM @tbl1 T2 WHERE T2.Status=0 AND T1.Name=T2.Name)
使用 EXISTS:
SELECT
*
FROM @tbl1 T1
WHERE EXISTS( SELECT T2.Name FROM @tbl1 T2 WHERE T1.Name=T2.Name AND T1.Status=1 GROUP BY T2.Name having count(T2.Status)=1 )
<强>输出:强>
答案 3 :(得分:1)
请试试这个
with cte as(
select 'A' name, 0 status
union all select 'A' name, 1 status
union all select 'B' name, 1 status
union all select 'C' name, 2 status
union all select 'D' name, 1 status
)
Select * from cte c
where NOT EXISTS (select 1 from cte cf where cf.status=0 AND c.name = cf.name)