我有一个包含3列的表格,第一列是“名称”。有些名称输入了两次,有些输入了3次,然后又输入了更多。我想为每个名称保留一个值,并根据第2列和第3列的值删除多余的行。如果第2列和第3列为空,我想删除该行。没有主键或id列。表格中大约有275万行。想要在SQL 14中使用一个查询(最好是一个查询)删除。有人可以帮忙吗?
Name column2 column3
Suzy english null
Suzy null null
Suzy null 5
John null null
John 7 7
George null benson
George null null
George benson null
George 5 benson
希望将其作为:
Name column2 column3
Suzy english null
Suzy null 5
John 7 7
George benson null
George 5 benson
提前谢谢了。
通过适当的顺序使用名称上的分区:
WITH cte as (
SELECT ROW_NUMBER()
OVER (PARTITION BY name
ORDER BY case
when column1 = 'null' and column2 = 'null' then 3
when column2 = 'null' then 2
when column1 = 'null' then 1
else 0 end
) num
FROM mytable
)
delete from cte where num > 1
这将删除重复项,并按优先级顺序保留行:
请注意,查询假设(基于对问题的评论)假设您的“ null”值实际上是文本字符串“ null”,而不是SQL null
。
如果它们实际上是空值,则替换= 'null'
为IS NULL
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句