如何使用MySQL获得以下结果

时间:2014-11-26 08:28:43

标签: mysql sql select group-by sql-order-by

您好我有一张名为orders_pending

的表格

它包含order_number列和model

order_number  | model

1                  1 
1                  2
2                  1
2                  3
2                  5
3                  5
4                  2

正如您所看到的,1个订单可以有多个模型,在我的表中没有唯一的密钥,但如果我同时接受订单号和模型,则它是唯一的。

我想要一个像这样的结果

order_number  | model

2                  1
2                  3
2                  5    
1                  1 
1                  2

只有order_number's只有model个{{1}},并且应根据表格中显示的订单数进行排序

我尝试了很多解决方案,但未能成功。

请帮忙。提前谢谢。

2 个答案:

答案 0 :(得分:4)

创建一个子查询,该子查询获取具有多个order_number的模型和过滤器models的总数。然后结果与表本身连接。使用TotalCount列对结果进行排序。

SELECT  a.*
FROM orders_pending a
     INNER JOIN
     (
        SELECT order_number, COUNT(*) TotalCount
        FROM  orders_pending
        GROUP BY order_number
        HAVING COUNT(*) > 1
     ) b ON a.order_number = b.order_number
ORDER BY b.TotalCount DESC, a.order_number, a.model

答案 1 :(得分:1)

首先我们得到的order_numbers有多个模型。

SELECT order_number, COUNT(*) AS how_many_orders
FROM
orders_pending
GROUP BY order_number 
HAVING COUNT(*) > 1;

然后我们加入这个来获取表中属于那些order_numbers的每一行。

SELECT 
op.order_number, op.model
FROM 
orders_pending op
INNER JOIN (

    SELECT order_number, COUNT(*) AS how_many_orders
    FROM
    orders_pending
    GROUP BY order_number 
    HAVING COUNT(*) > 1

) sq ON op.order_number = sq.order_number
ORDER BY how_many_orders, op.order_number