根据 SQL Server 2008 R2 中的最大值删除一行
Deleting a row based on the max value in SQL Server 2008 R2
我有@RankTable
table,其中包含不同客户的借记。从这里我想删除每个排名最高的客户。
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
我希望上述 table 的输出是:
我想删除排名最高的客户。
ex:I 想要删除 Customer_ID = 4 的行,其中 Rank1 = 20(对所有客户都是这样),但我无法删除
使用 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;
这会起作用-
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
我有@RankTable
table,其中包含不同客户的借记。从这里我想删除每个排名最高的客户。
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
我希望上述 table 的输出是: 我想删除排名最高的客户。 ex:I 想要删除 Customer_ID = 4 的行,其中 Rank1 = 20(对所有客户都是这样),但我无法删除
使用 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;
这会起作用-
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