从表中删除至少一个值为 NULL 的行

Mic*_*ael 1 sql t-sql sql-server common-table-expression sql-delete

我在 MS SQL Server 中有下表:

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
Run Code Online (Sandbox Code Playgroud)

我想删除同一地址中的所有行,其中至少有一个 personnum = NULL

所以从上面,我需要删除 RowID 的 1、2、3、6、7、8。

RowID 的 4 和 5 没问题,因为它们有一个 PersonNum。我如何在 T SQL 中实现这一点?这可以使用 CTE 吗?

Yog*_*rma 5

您可以使用EXISTS:

DELETE t
FROM table t
WHERE EXISTS (SELECT 1 
              FROM table t1 
              WHERE t1.Address1 = t.Address1 AND t1.PersonNum IS NULL
             ); 
Run Code Online (Sandbox Code Playgroud)