获得最多的产品

时间:2013-09-27 21:30:37

标签: mysql sql

目标

我想进行排名,我需要获得一个列的10个第一。

问题

我的申请表中有以下表格:

+------+---------+
| User | Product |
+------+---------+
| 1    | 1       |
+------+---------+
| 2    | 1       |
+------+---------+
| 3    | 1       |
+------+---------+
| 4    | 1       |
+------+---------+
| 5    | 2       |
+------+---------+
| 6    | 2       |
+------+---------+
| 7    | 2       |
+------+---------+
| 8    | 3       |
+------+---------+
| 9    | 3       |
+------+---------+

我想按照这种模式进行排名:

+---------+----------+
| Product | Quantity |
+---------+----------+
| 1       | 4        |
+---------+----------+
| 2       | 3        |
+---------+----------+
| 3       | 2        |
+---------+----------+

我该怎么做?

2 个答案:

答案 0 :(得分:3)

你可以这样做:

SELECT product, COUNT(product)
FROM yourtable
GROUP BY product
ORDER BY COUNT(product) DESC
LIMIT 10;

答案 1 :(得分:0)

这样的事情应该这样做。

SELECT TOP 10 Product, COUNT(*)
FROM Table
GROUP BY Product
ORDER BY COUNT(*) DESC;