2016-11-11 49 views
1

我有一個SQL問題,我無法處理。從表中刪除NULL行,並且具有相同的日期

我需要從表中刪除行,它們是date_to列中的NULL,但與date_from列具有不同的值。

table

我想刪除的列是一個用數字3

它在date_from相同的值,併爲空。

這是我自己的方法:

select 
    date_from, id, count(*) number_of_rows_with_the_same_datefrom 
from 
    test 
group by 
    date_from, id 
having 
    count(*) > 1 

這將返回所有具有從日期同一ID同一從那裏我失去了:)

回答

2

另一種選擇是使用CTE和ROW_NUMBER()

;with cte as (
    Select * 
      ,RN=Row_Number() over (Partition By ID, date_from Order by date_to Desc) 
    From YourTable 
) 
Select *  --<< Remove if Satisfied 
--Delete  --<< Remove comment if Statisfied 
From cte 
Where RN>1 and date_to is null 

返回(記錄被刪除)

ID name date_from date_to RN 
2 Jim  2012-08-01 NULL 2 
+0

感謝它的工作,flawlesly。我用了1個小時,完全失去了。這看起來很簡單,但結果很困難。 – uba2012

+0

你能解釋一下thos是如何工作的嗎? – uba2012

+0

@ uba2012如你所知,刪除應該非常小心,我犯了很大的錯誤。 CTE或公用表表達式可能非常有用。此外,您應該熟悉Window函數/ OVER子句。只需在CTE中運行select就可以更好地查看Row_Number()在做什麼。 –

0

使用一個存在的語句行,這看起來應該非常簡單。

DELETE FROM table A 
WHERE exists (SELECT 1 
       FROM table B 
       WHERE A.Id = B.ID 
       and A.Date_from = B.date_from 
       and A.Name = B.Name 
       and B.Date_To is null) 

假設ID和姓名以及date_from使某種關鍵的......我會更舒服知道PK是在該表上的內容。 (或一個唯一的索引,如果存在的話)

驗證它會做你想做的事;先運行這個。

SELECT * 
FROM table A 
WHERE exists (SELECT 1 
       FROM table B 
       WHERE A.Id = B.ID 
       and A.Date_from = B.date_from 
       and A.Name = B.Name 
       and B.Date_To is null) 
+0

嗨,我跑了SELECT語句,但它不工作。它找到2行。並且表中沒有鑰匙 – uba2012

+0

您好xQbert它的類型=日期 – uba2012

+0

嗯..不知道那麼。我看不出爲什麼這會起作用。除非名稱中有空格或ID中有空格......(這就是爲什麼我關心唯一索引)以及爲什麼生成一個rownumber作爲唯一鍵可能是最好的方法。 – xQbert

相關問題