簡體   English   中英

從表中刪除至少一個值為 NULL 的行

[英]Delete rows from table where at least one of the values is NULL

我在 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

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

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

RowID 的 4 和 5 沒問題,因為它們有一個 PersonNum。 我如何在 T SQL 中實現這一點? 這可以使用 CTE 嗎?

您可以使用EXISTS

DELETE t
FROM table t
WHERE EXISTS (SELECT 1 
              FROM table t1 
              WHERE t1.Address1 = t.Address1 AND t1.PersonNum IS NULL
             ); 

考慮這個 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

內窗max()檢查是否至少一個記錄有一個PersonNumnull用於當前Address1 外部查詢刪除標記的記錄。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM