我的表格如下
客户
客户表格中包含以下列
sales_ID varchar(50)
product_ID int
ProcessNumber int
CreateDate datetime
客户表的数据如下
1。行
sales_Id "00000020041"
product_ID 1733
ProcessNumber 15
2。行
sales_Id "00000020041"
product_ID 1733
ProcessNumber 15
第3。行
sales_Id "00000020041"
product_ID 1733
ProcessNumber 15
问题:
我想删除除了查询的一行以外的所有行。
我在下面试过
;with cte as
(
select *,row_number() over(order by sales_ID) RN
FROM Customer
where sales_Id = sales_Id
and product_ID = product_ID
and ProcessNumber = ProcessNumber)
delete from cte where RN>1
然而,我所尝试的并不适合我。
如果sales_ID和product_Id以及ProcessNumber等于sales_ID和product_Id以及ProcessNumber ,我如何删除除一行之外的所有行?
答案 0 :(得分:1)
您需要在PARTITION BY
中使用ROW_NUMBER()
;with cte as
(
select *,row_number() over(PARTITION BY sales_Id,product_ID,ProcessNumber order by (SELECT 1)) RN
FROM Customer
where sales_Id = sales_Id
and product_ID = product_ID
and ProcessNumber = ProcessNumber)
delete from cte where RN>1
答案 1 :(得分:1)
您不需要CTE
和WHERE
子句。以下就足够了。
DELETE FROM (
select *,
row_number() over(
PARTITION BY sales_Id,product_ID,ProcessNumber
ORDER BY Sales_ID
) rown
FROM Customer
)tbl where rown > 1
答案 2 :(得分:1)
在这种情况下,您需要使用DELETE tbl FROM(...)tbl而不是DELETE FROM(...)tbl。
DELETE tbl
FROM
(
SELECT *,
row_number() over(
PARTITION BY sales_Id,product_ID,ProcessNumber
ORDER BY Sales_ID
) RowNumber
FROM Customer
)tbl
WHERE RowNumber > 1