MySQL First GROUP BY,然后是ORDER

时间:2014-04-03 13:39:45

标签: mysql sql

我一直在搜索,但无法找到合适的解决方案来排序我的桌子' shop'。

它的外观如下:

Product           Price
---------------------------------
Site 1             35
Site 2             50
Site 3             15
Site 1             30
Site 2              5

现在我需要它看起来像这样:

Product           Price
---------------------------------
Site 2             50
Site 2              5
Site 1             35
Site 1             30
Site 3             15

表格应从最高价格开始排序,然后按产品分组。 我尝试了一百万个不同的查询,我得到的最接近的是:

SELECT m.* FROM shop m
    INNER JOIN
        (SELECT product, MAX(price) AS maxprice FROM shop GROUP BY product ORDER BY maxprice ASC) s
    ON m.product = s.product
ORDER BY s.maxprice DESC

查询完成了它的工作,但是错误地对组中的价格进行排序。

Product           Price
---------------------------------
Site 2              5
Site 2             50
Site 1             30
Site 1             35
Site 3             15

我做错了什么?非常感谢帮助!

最好,感谢百万!

2 个答案:

答案 0 :(得分:1)

Select x.product, x.price from 
(Select product, max(price) as mprice from shop
group by product) as tbl inner join shop x on tbl.product = x.product
order by tbl.mprice desc, x.Price desc

我也注意到你创造了一个小提琴会节省我一些时间,但这里是更新小提琴

SELECT s.product, s.Price
from (Select product, max(price) as mprice
   from shop group by product) as tbl
   inner join shop s on s.product = tbl.product
order by tbl.mprice desc, s.price desc

http://sqlfiddle.com/#!2/c5eb64/3

答案 1 :(得分:0)

您有两个级别的排序,因此您需要在ORDER BY中描述这两个级别

ORDER BY s.maxprice DESC, m.price DESC