繁体   English   中英

1个具有最大值的不同行

[英]1 distinct row having max value

这是我的数据

在此处输入图片说明

我需要具有max(Price)的唯一ID(1行)。 因此,输出为:

在此处输入图片说明

我尝试了以下

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

给出问题作为输出,因为没有键。 我也尝试了其他where条件,这将原始表作为输出。

您可以在SQL Server中尝试以下操作:

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

数据

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');

询问

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;

结果

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

说明

在您的数据集中,ID 1有2条价格相同的记录。 您必须决定要选择哪个。 因此,在上面的示例中,我为姓名按字母顺序最低的用户显示了一条记录。

替代方法

SQL Server具有排名函数row_number over()也可以使用:

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

子查询说-给我表中的所有记录,并给每行一个序列号,每个ID均以1开头。 这些行应先按ID排序,然后按价格降序排列,然后按usr排序。 外部查询选择sr号为1的记录。

此处的示例: https//rextester.com/KZCZ25396

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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