简体   繁体   中英

Fetch Column based on another Column maximum value

create table demo11 (dn int, rn varchar(max))
insert into demo11 values(1,'A'),(1,'A-1'),(1,'A-3'),(2,'A'),(2,'B'),(2,'C')


-------------
|dn |rn |
-------------
|1  |A  |
|1  |A-1|
|1  |A-3|
|2  |A  |
|2  |B  |
|2  |C  |
-------------

Expected Result: delete (1 A, 1 A-1, 2 A, 2 B) result 1 A-3, 2 C

rows which are to be delted:1,2,4,5

You could rank the rows based on rn per each dn , and take the first one:

SELECT dn, rn
FROM   (SELECT dn, rn, RANK() OVER (PARTITION BY dn ORDER BY rn DESC) AS rk
        FROM   mytable)
WHERE  rk = 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM