我有一个表格(表1),其中包含order_item_id
customer_id
和order_id
列,其中我想计算每个客户的订单数量。很遗憾,包含多篇文章的订单具有相同的order_id
|order_item_id|order_id|customer_id|
| 2 | 30 | 1 |
| 3 | 30 | 1 |
| 4 | 42 | 1 |
| 5 | 33 | 2 |
| 11 | 32 | 3 |
| 12 | 33 | 2 |
| 13 | 33 | 2 |
| 19 | 69 | 3 |
预期结果:
|numberOfOrders|customer_id|
| 2 | 1 |
| 1 | 2 |
| 2 | 3 |
我试过这个(以及更多):
CREATE TABLE X AS
SELECT
customer_id,
COUNT(order_id) AS `numberOfOrders`
FROM Table1 T1
GROUP BY customer_id;
问题在于,使用此解决方案,它会计算每个商品而不是订单数量:因此客户1的订单数量为3(不是2),而客户2的订单数量为3(不是1).... < / p>
如何使用Mysql查询为大型数据库解决这个问题?
答案 0 :(得分:2)
按预期尝试以下SELECT
数据解决方案:
SELECT COUNT(DISTINCT order_id) AS numberOfOrders, customer_id
FROM table1
GROUP BY customer_id
答案 1 :(得分:0)
一个选项可能是GROUP
两次。每个订单的商品数量首先GROUP
,每个客户的订单数量由第二个GROUP
包裹:
/* second group */
SELECT customer_id
, count(*) AS number_of_orders
FROM (
/* first group */
SELECT order_id
, customer_id
, count(*) AS order_item_count
FROM Table1
GROUP BY order_id, customer_id
) a
GROUP BY customer_id