[英]Retaining higher value and deleting lower value in SQL
Happy New Year.新年快乐。
I am unsure how to do an SQL where I need to retain the record for clientID with the highest level while deleting the others?我不确定如何执行 SQL ,我需要保留最高级别的 clientID 记录,同时删除其他记录?
My Table is like below我的表如下
And would like to have below并想在下面
Basically, it removes the duplicate clientID row but retain the highest level of that clientID record.基本上,它删除了重复的 clientID 行,但保留了该 clientID 记录的最高级别。
Thank you for any guidance.感谢您的任何指导。
This query will work in most variants of SQL (not MySQL < 8.0 or SQL Server);此查询适用于 SQL 的大多数变体(不是 MySQL < 8.0 或 SQL 服务器); it uses
ROW_NUMBER()
to rank the Level
values by ClientID
and removes all rows other than the row with the maximum Level
for that ClientID
value:它使用
ROW_NUMBER()
按ClientID
对Level
值进行排名,并删除除具有该ClientID
值的最大Level
的行之外的所有行:
WITH CTE AS (
SELECT ClientID, Level,
ROW_NUMBER() OVER (PARTITION BY ClientID ORDER BY Level DESC) AS rn
FROM data
)
DELETE FROM data
WHERE (ClientId, Level) IN (
SELECT ClientId, Level
FROM CTE
WHERE rn > 1
)
SQLite Demo on dbfiddle dbfiddle 上的 SQLite 演示
In SQL Server you can simply delete from the CTE:在 SQL 服务器中,您可以简单地从 CTE 中删除:
WITH CTE AS (
SELECT ClientID, Level,
ROW_NUMBER() OVER (PARTITION BY ClientID ORDER BY Level DESC) AS rn
FROM data
)
DELETE FROM CTE
WHERE rn > 1
Demo on dbfiddle dbfiddle 上的演示
In MySQL < 8.0, you can use this query:在 MySQL < 8.0 中,您可以使用此查询:
DELETE FROM data
WHERE (ClientID, Level) NOT IN (
SELECT ClientID, MAX(Level)
FROM (SELECT * FROM data) d
GROUP BY ClientID
)
You can use the exists
as follows:您可以按如下方式使用
exists
:
Delete from your_table t
Where exists
(Select 1 from your_table tt
Where tt.client_id = t.client_id and tt.level > t.level)
In Mysql
you can simple access the desired output without deleting the data in sql在
Mysql
,您可以简单地访问所需的 output 而无需删除 sql 中的数据
SELECT ClientID,level FROM (SELECT* , ROW_NUMBER() OVER(PARTITION BY ClientID
ORDER BY level DESC ) AS RN FROM tbl_client)A
WHERE RN=1
Here is the simple Desired output这是简单的 Desired output
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.