从SQL中的临时表中删除重复的行

时间:2017-05-16 17:40:53

标签: sql-server

我有一个包含以下列的表

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

我需要删除具有相同AssId和QuestionID的answertext null行 最终输出需要采用这种格式

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

请帮我解决删除查询

提前致谢 SREE

2 个答案:

答案 0 :(得分:1)

你可以使用exists来查看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
)

答案 1 :(得分: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