从 table 中删除至少有一个值为 NULL 的行
Delete rows from table where at least one of the values is NULL
我在 MS SQL 服务器中有以下 table:
RowID PersonNum Address1
1 456 1 My street
2 NULL 1 My street
3 789 1 My street
4 987 2 My street
5 963 2 My street
6 852 3 My street
7 741 3 My street
8 NULL 3 My street
我想删除同一地址中至少有一个 personnum = NULL
的所有行
所以根据上面的内容,我需要删除 RowID 的 1、2、3、6、7、8。
RowID 的 4 和 5 可以,因为它们有一个 PersonNum。我如何在 T SQL 中实现这一点?这可能使用 CTE 吗?
考虑这个 CTE 解决方案:
with cte as (
select
max(case when PersonNum is null then 1 end) over(partition by Address1) has_null
from mytable
)
delete from cte where has_null = 1
内部 window max()
检查是否至少有一个记录有一个 PersonNum
,即当前 Address1
的 null
。外部查询删除标记的记录。
您可以使用 EXISTS
:
DELETE t
FROM table t
WHERE EXISTS (SELECT 1
FROM table t1
WHERE t1.Address1 = t.Address1 AND t1.PersonNum IS NULL
);
我在 MS SQL 服务器中有以下 table:
RowID PersonNum Address1
1 456 1 My street
2 NULL 1 My street
3 789 1 My street
4 987 2 My street
5 963 2 My street
6 852 3 My street
7 741 3 My street
8 NULL 3 My street
我想删除同一地址中至少有一个 personnum = NULL
的所有行所以根据上面的内容,我需要删除 RowID 的 1、2、3、6、7、8。
RowID 的 4 和 5 可以,因为它们有一个 PersonNum。我如何在 T SQL 中实现这一点?这可能使用 CTE 吗?
考虑这个 CTE 解决方案:
with cte as (
select
max(case when PersonNum is null then 1 end) over(partition by Address1) has_null
from mytable
)
delete from cte where has_null = 1
内部 window max()
检查是否至少有一个记录有一个 PersonNum
,即当前 Address1
的 null
。外部查询删除标记的记录。
您可以使用 EXISTS
:
DELETE t
FROM table t
WHERE EXISTS (SELECT 1
FROM table t1
WHERE t1.Address1 = t.Address1 AND t1.PersonNum IS NULL
);