Id1 Id2
20441 20441
20441 26397
20441 37631
20441 82693
20441 1015597
37631 20441
37631 36551
37631 37631
我在上表中有数据,我想标记为 IsDeleted 如果Id1的值为37631(如果Id1列中已存在Id2列值,则将IsDeleted作为1)。
基本上我想要输出如下,
Id1 Id2 IsDeleted
20441 20441 0
20441 26397 0
20441 37631 0
20441 82693 0
20441 1015597 0
37631 20441 1
37631 36551 1
37631 37631 1
我该怎么做? 这里标记为IsDeleted = 1的优先顺序是Id1升序。
答案 0 :(得分:0)
案例应符合您的要求,除非我遗漏了一些事情
select *,
case
when exists(select 1 from table t2 where t1.id2=t2.id1)
then 1 else 0 end 'Deleted'
from
table t1
order by id1
您所需的输出也是错误的(例如,1015597不存在,因此它将为零)
答案 1 :(得分:0)
也许,我不明白问题。但为什么这个变体并不适合你。
UPDATE t1
SET
t1.IsDeleted = 1
FROM Table1 t1
JOIN Table1 t2
ON (t1.id1 = t2.id2 AND t1.IsDeleted <> 1)
或者如果您需要选择
SELECT
t1.id1,
t1.id2,
CASE
WHEN t2.Id1 IS NULL THEN 0
ELSE 1
END IsDeleted
FROM
Table1 t1
LEFT JOIN Table1 t2
ON (t1.id1 = t2.id2)
ORDER BY
IsDeleted
答案 2 :(得分:0)
你可以试试这个:
SELECT t1.id ,t1.pid ,
CASE WHEN EXISTS ( SELECT TOP 1 *
FROM dbo.tbl AS t2
WHERE t2.id < t1.id
AND t1.Id = t2.pid ) THEN 1
ELSE 0
END AS IsDeleted
FROM dbo.tbl AS t1;