Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

sql server - 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?

My Table is like below

Table

And would like to have below

enter image description here

Basically, it removes the duplicate clientID row but retain the highest level of that clientID record.

Thank you for any guidance.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This query will work in most variants of SQL (not MySQL < 8.0 or SQL Server); 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:

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

In SQL Server you can simply delete from the 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

In MySQL < 8.0, you can use this query:

DELETE FROM data
WHERE (ClientID, Level) NOT IN (
  SELECT ClientID, MAX(Level)
  FROM (SELECT * FROM data) d
  GROUP BY ClientID
)

Demo on dbfiddle


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...