需要帮助对可用的order details表进行分组,以得到count(order\u line\u item)、qty和count(qty)的分布

uurv41yg  于 2021-07-29  发布在  Java
关注(0)|答案(1)|浏览(389)

我有一张订货单,上面有以下信息
订单id、产品id、订购数量

OID PID Qty
1   10  1
1   20  2
2   10  2
2   40  4
3   50  1
3   20  3
4   30  1
4   90  2
4   90  5
5   10  2
5   20  2
5   70  5
5   60  1
6   80  2

如果我运行以下查询

select `Qty`, count(`Qty`) 
from `table`
group by `Qty`

我得到了表中数量的分布,这是

Qty count(`Qty`)
1   4
2   6 
3   1
4   1
5   2

我还想找出订单\行\项目级别的数量分布
也就是说,有多少订单有一个行项目,有1个数量的项目,2个数量的项目,等等

Count(Order_line_item)    Qty        Count(Qty)
1                         2          1
2                         1          2
2                         2          2
2                         3          1
2                         4          1
3                         1          1
3                         2          1
3                         5          1
4                         1          1
4                         2          2
4                         5          1

我应该在上面的查询中做什么修改来实现这一点

qij5mzcb

qij5mzcb1#

尝试此查询

SELECT  count_order_line_items, `Qty`, count(*)
FROM (
   SELECT count(*) over (partition by `OID`) as count_order_line_items,
         `Qty`
   FROM Table1
) x
GROUP BY count_order_line_items, `Qty`

演示:https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=07dfb27a7d434eca1f0b9641aadd53c8
如果你的mysql版本低于8,那么试试这个

SELECT count_order_line_items, `Qty`, count(*)
FROM Table1 t1
JOIN (
   SELECT `OID`, count(*) as count_order_line_items
   FROM Table1
   GROUP BY `OID`
) t2 ON t1.`OID` = t2.`OID`
GROUP BY count_order_line_items, `Qty`

演示:https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=28c291a4693f31029a103f5c41a97d77

相关问题