2017-05-16 37 views
0

我有一個表的下方列刪除臨時表中重複行的SQL

+-------+------------+------------+ 
| AssID | QuestionID | AnswerText | 
+-------+------------+------------+ 
| 12 |   34 | Null  | 
| 12 |   34 | Sample  | 
| 13 |   35 | null  | 
| 13 |   35 | test1  | 
+-------+------------+------------+ 

我需要刪除answertext空一行相同ASSID和QuestionID 最終輸出需要在此格式

+-------+------------+------------+ 
| AssId | QuestionID | AnswerText | 
+-------+------------+------------+ 
| 12 |   34 | Sample  | 
| 13 |   35 | test1  | 
+-------+------------+------------+ 

請幫我刪除查詢

在此先感謝 SREE

回答

0

您可以使用CTE和ROW_NUMBER刪除

;with cte as (
    select *, RowN = Row_number() over (partition by assid, questionid order by answertext) from yourtable 
    )--or order by your id because you have not provided logic for which one to select in answertext 
delete from cte where RowN > 1 
+0

如果你通過answertext命令,你將刪除非null值並保留null值。與預期輸出的結果相反 – JamieD77

+0

是的,因爲你需要通過任何實際定義輸出的rowid來進行排序。我在評論中提到了這一點 –

1

可以使用存在,看看是否NULL answerText行也有一個非空answerText行

DELETE t 
FROM MyTABLE t 
WHERE t.AnswerText IS NULL 
     AND EXISTS 
(
    SELECT * 
    FROM MyTable m 
    WHERE m.AssID = t.AssID 
      AND m.QuestionID = t.QuestionID 
      AND m.AnswerText IS NOT NULL 
) 
+0

由於傑米,它完美地工作: - ) – Sree