按分组选择中的字段数对SQL查询进行排序

时间:2013-04-17 10:05:02

标签: mysql sql sorting

我有这张桌子,

CREATE TABLE `Products` (
  `product_id` int(11) NOT NULL AUTO_INCREMENT,
  `product` varchar(45) DEFAULT NULL,
  `added_by` varchar(45) DEFAULT NULL,
  `list_name` varchar(45) NOT NULL,
  PRIMARY KEY (`product_id`)
) ENGINE=MyISAM AUTO_INCREMENT=231 DEFAULT CHARSET=utf8

我想要一个sql查询,这样我就可以获得一组同名产品,这些产品按哪个组排在最顶层,最少排在最底层

这是我到目前为止所做的,但它只是按字母顺序对这些组进行排序

SELECT product FROM Products GROUP BY product ORDER BY product

我在此结尾添加什么来计算并按每个组中的条目数排序?

2 个答案:

答案 0 :(得分:3)

SELECT product, COUNT(*) AS NumberOfEntries 
FROM Products 
GROUP BY product 
ORDER BY NumberOfEntries DESC

详细了解汇总函数here

答案 1 :(得分:0)

您可以尝试这样的事情:

SELECT product
FROM
(
    SELECT product, COUNT( 1 ) AS num_products
    FROM products
    GROUP BY product
) AS t
ORDER BY num_products DESC