简体   繁体   中英

1 distinct row having max value

This is the data I have

在此处输入图片说明

I need Unique ID(1 row) with max(Price). So, the output would be:

在此处输入图片说明

I have tried the following

select * from table a
join (select b.id,max(b.price) from table b
group by b.id) c on c.id=a.id;

gives the Question as output, because there is no key. I did try the other where condition as well, which gives the original table as output.

You could try something like this in SQL Server:

Table

create table ex1 (
    id int, 
    item char(1),
    price int,
    qty int,
    usr char(2)
);

Data

insert into ex1 values
(1, 'a', 7, 1, 'ab'),
(1, 'a', 7, 2, 'ac'),
(2, 'b', 6, 1, 'ab'),
(2, 'b', 6, 1, 'av'),
(2, 'b', 5, 1, 'ab'),
(3, 'c', 5, 2, 'ab'),
(4, 'd', 4, 2, 'ac'),
(4, 'd', 3, 1, 'av');

Query

select a.* from ex1 a
join (
    select id, max(price) as maxprice, min(usr) as minuser
    from ex1
    group by id
) c
    on c.id = a.id
    and a.price = c.maxprice
    and a.usr = c.minuser
order by a.id, a.usr;

Result

id  item price qty  usr
1   a     7    1    ab
2   b     6    1    ab
3   c     5    2    ab
4   d     4    2    ac

Explanation

In your dataset, ID 1 has 2 records with the same price. You have to make a decision which one you want. So, in the above example, I am showing a single record for the user whose name is lowest alphabetically.

Alternate method

SQL Server has ranking function row_number over() that can be used as well:

select * from (
    select row_number() over( partition by id order by id, price desc, usr) as sr, *
    from ex1
) c where sr = 1;

The subquery says - give me all records from the table and give each row a serial number starting with 1 unique to each ID. The rows should be sorted by ID first, then price descending and then usr. The outer query picks out records with sr number 1.

Example here: https://rextester.com/KZCZ25396

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