计算不同的产品

时间:2013-08-01 23:59:19

标签: mysql sql

我有下表:

order_id  product_id
1         102
2         105
3         102
4         96
5         96

我如何获得product_id的计数。我希望达到的结果是:

product_id    count
96            2
102           2
105           1

我尝试的查询是:

SELECT product_id, sum(product_id) from orders

但是这当然只会产生一行不正确的结果。这里的正确查询是什么?

2 个答案:

答案 0 :(得分:3)

SELECT product_id, COUNT(*) FROM orders GROUP BY product_id

或者如果你想给它命名......

SELECT product_id, COUNT(*) as product_count FROM orders GROUP BY product_id

答案 1 :(得分:0)

试试这个

 SELECT product_id, count(*) as count  from orders GROUP BY product_id