查询以获得分组结果

时间:2016-02-11 06:03:22

标签: mysql sql

我有一个简单的表Customersfields id, name, rating, seller_id。 查询结果

select seller_id, MAX(rating) 
from Customer 
group by seller_id

是按seller_id分组的客户,其评分的最大值。像这样:

seller_id  rating
2          17
3          20
4          17

如何修改此查询以另外获取客户的ID?如果我将id添加到SELECT我收到错误,我应该添加id分组。但是我想只获得指定id的上面显示的值。有谁知道如何做到这一点?谢谢。

4 个答案:

答案 0 :(得分:0)

试试这个

select c1.* from Customer c1 inner join 
(select seller_id, MAX(rating) as rating from Customer 
group by seller_id) c2 on c1.rating  = c2.rating

 SELECT c1.* FROM Customer b1 LEFT JOIN Customer c2
 ON (b1.seller_id = b2.seller_id  AND b1.rating > b2.br_created_date)
 WHERE b2.rating is null;

答案 1 :(得分:0)

尝试:

select t.id, t.seller_id, t.rating
from Customer c
join (
    select seller_id, MAX(rating) rating
    from Customer 
    group by seller_id
) x
on x.seller_id = c.seller_id
and x.rating = c.rating

答案 2 :(得分:0)

SimarjeetSingh有一个很好的答案。再调整一下:

select c.customer_id, c.seller_id
from customer c
join (
  select seller_id, max(rating) max_rating
  from customer
  group by seller_id
) s 
  on c.seller_id = s.seller_id
  and c.rating = s.max_rating

这样您就可以比较seller_id和最高评分。

答案 3 :(得分:0)

数据集分为 使用GROUP BY子句的组。 分组属性很常见 每个小组成员共享的密钥。 分组属性通常是单个属性 列但可以是多列或 一个不能基于的表达式 小组职能。请注意,仅分组 属性和组功能是 使用时在SELECT子句中允许使用 GROUP BY。

参考这个 Select EMP with max SAL from each DEPT

相关问题