且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

T-SQL:删除所有重复行但保留一个

更新时间:2023-02-06 11:44:10

你没有说你用的是什么版本,但在 SQL 2005 及以上,你可以使用带有 结束条款.它有点像这样:

You didn't say what version you were using, but in SQL 2005 and above, you can use a common table expression with the OVER Clause. It goes a little something like this:

WITH cte AS (
  SELECT[foo], [bar], 
     row_number() OVER(PARTITION BY foo, bar ORDER BY baz) AS [rn]
  FROM TABLE
)
DELETE cte WHERE [rn] > 1

尝试一下,看看你会得到什么.

Play around with it and see what you get.

(为了提供帮助,有人编辑了 CTE 中的 ORDER BY 子句.要清楚的是,您可以在此处按任何您想要的顺序排序,它不必是其中之一cte 返回的列.事实上,这里的一个常见用例是foo, bar"是组标识符,而baz"是某种时间戳.​​为了保持最新,你会做 ORDER BY baz desc)

( In an attempt to be helpful, someone edited the ORDER BY clause within the CTE. To be clear, you can order by anything you want here, it needn't be one of the columns returned by the cte. In fact, a common use-case here is that "foo, bar" are the group identifier and "baz" is some sort of time stamp. In order to keep the latest, you'd do ORDER BY baz desc)