2

我有这张桌子,

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

我要在最后添加什么以按每组中的条目数进行计数和排序?

4

2 回答 2

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

在此处阅读有关聚合函数的更多信息。

于 2013-04-17T10:07:40.813 回答
0

你可以尝试这样的事情:

SELECT product
FROM
(
    SELECT product, COUNT( 1 ) AS num_products
    FROM products
    GROUP BY product
) AS t
ORDER BY num_products DESC
于 2013-04-17T10:09:52.443 回答