我有两个表连接和分组,一个是Orders,另一个是Items 我想得到的是我们在x期间的订单数量。
所以我最初的想法是首先得到每个订单在数据集中出现的时间的计数,然后将每一行除以上面的数字,例如,订单ID 1出现3次,因此计数将是.33 * 3 = 1个订单。
但是我在第一步遇到麻烦,正确计算order.id次数。
我希望展示的是:
+-------+---------+------+
|order |item |count |
|number | | |
+-------+---------+------+
| 1 | ABC | 3 |
+-------+---------+------+
| 1 | DEF | 3 |
+-------+---------+------+
| 1 | GHI | 3 |
+-------+---------+------+
| 2 | ABC | 2 |
+-------+---------+------+
| 2 | DEF | 2 |
+-------+---------+------+
| 3 | ABC | 1 |
+-------+---------+------+
但我只是这样:
+-------+---------+------+
|order |item |count |
|number | | |
+-------+---------+------+
| 1 | ABC | 1 |
+-------+---------+------+
| 1 | DEF | 1 |
+-------+---------+------+
| 1 | GHI | 1 |
+-------+---------+------+
| 2 | ABC | 1 |
+-------+---------+------+
| 2 | DEF | 1 |
+-------+---------+------+
| 3 | ABC | 1 |
+-------+---------+------+
这是我的疑问:
SELECT
`orders`.`id` as 'order number',
`item`.`item`,
COUNT(`orders`.`id`) as ' count'
FROM `db`.`orders`
LEFT JOIN `item` ON `item`.`order_id` = `order`.`order_id`
GROUP BY `orders`.`id`, `item`.`item`
;
如何?
答案 0 :(得分:0)
您的查询应该是 -
SELECT
`item`.`item`,
COUNT(`orders`.`id`) as 'count'
FROM `db`.`orders`
JOIN `item` ON `item`.`order_id` = `order`.`order_id`
GROUP BY `item`.`item`;
我不认为您需要多次使用相同的项目行,因为您正在尝试逐项计数。
更新:你可以通过这个获得你想要的结果
SELECT t1.order_id, t2.item, t1.cnt FROM
(
SELECT o.order_id,COUNT(i.items) cnt FROM
item i
JOIN orders o ON o.order_id=i.order_id
group by o.order_id
) t1
JOIN
item t2 ON t1.order_id=t2.order_id;
答案 1 :(得分:0)
你应该尝试以下,
Select
`order`.`order_id`,
`item`.`item`,
`order`.`count`
from
(
SELECT
`orders`.`id` as order_id,
COUNT(*) as 'count'
FROM `db`.`orders`
group by `orders`.`id`
) as order
JOIN `item` ON `item`.`order_id` = `order`.`order_id`
答案 2 :(得分:0)
在朋友的帮助下,我最终得到了我想要的东西,使用以下内容:
SELECT
orders.id as 'order number',
items.item,
(SELECT count(*) FROM db.items where items.id = sales.id) as 'order_count'
FROM db.orders
GROUP BY orders.id, items.item
;