根据SQL Server 2008 R2中的最大值删除行

时间:2019-05-16 07:36:45

标签: sql sql-server-2008-r2

enter image description here

我有@RankTable表,其中包含不同客户的借方。我要从中删除每个具有最高排名的客户。

Declare @RankTable Table
(
   Customer_ID int,
   Debit decimal(18,2),
   Transaction_Date datetime,
   Sales_Master_ID int,
   Rank int,
   Rank1 int
)
Insert into @RankTable
  Select *,row_number()over(partition by (Customer_ID)  Order By 
    Customer_ID)as Rank1 
From @tempTable


Select  Customer_ID,Debit,Transaction_Date ,Sales_Master_ID,Rank1 from 
@RankTable Order By Customer_ID

我希望上表的输出为: 我想删除排名最高的客户。 例如:我想删除具有Rank1 = 20的Customer_ID = 4行(所有客户都这样),但是我无法删除

2 个答案:

答案 0 :(得分:2)

使用CTE,将其定位为每个客户的最高排名记录。

WITH cte AS (
    SELECT *,
        ROW_NUMBER() OVER (PARTITION BY Customer_ID ORDER BY Rank1 DESC) rn
    FROM @RankTable
)

DELETE
FROM cte
WHERE rn = 1;

答案 1 :(得分:0)

这将起作用-

DELETE A
FROM @RankTable A
INNER JOIN
(
    SELECT ID,MAX(Rank1) Rank1
    FROM @RankTable 
    GROUP BY ID
) B
ON A.id = B.id and A.Rank1 = B.Rank1