我正在尝试编写一个有效的查询,如下所示
"获取所有已删除且没有其他行具有相同值且未删除的行"
实施例
------------------------
| 2 | "bar" | 1
------------------------
| 4 | "baz" | 1
------------------------
| 6 | "baz" | 1
------------------------
======>
foo
结果集中deleted = 0
行未包含的原因是因为其中一行 put returns between paragraphs
for linebreak add 2 spaces at end
indent code by 4 spaces
。
答案 0 :(得分:2)
检查此查询
select
a.*
from
myTable a
where
not exists (
select 1
from mytable b
where
a.val = b.val
and b.deleted = 0
)
这是您可能感兴趣的一个article
答案 1 :(得分:1)
为了获取已删除的值而不是其他值,您可以使用subquery
形式,其中子查询仅返回已删除的值为1的值。
SELECT * FROM table
WHERE val IN (
SELECT val FROM table
GROUP BY val
HAVING COUNT(DISTINCT deleted) = 1 AND
COUNT(DISTINCT case when deleted = 1 then deleted end) = 1
)
相关的子查询可能很有用
SELECT * FROM table t
WHERE EXISTS (
SELECT val FROM table
WHERE val = t.val
GROUP BY val
HAVING COUNT(DISTINCT deleted) = 1 AND
COUNT(DISTINCT case when deleted = 1 then deleted end) = 1
)
答案 2 :(得分:0)
如果您喜欢我喜欢加入条款,这是一个选项:)
declare @t table(id int, val varchar(50) ,deleted bit)
insert into @t(id,val,deleted)
values
(1,'foo',1)
,(2,'bar',1)
,(3,'foo',0)
,(4,'baz',1)
,(5,'qux',0)
,(6,'baz',1)
select *
from @t t1
left join(select distinct t2t1.val from @t t2t1 where deleted=0) t2 on t1.val=t2.val
where t2.val is null