gpt4 book ai didi

mysql - 复杂的查询 - 很少有包含分组列的表

转载 作者:行者123 更新时间:2023-11-29 01:59:17 24 4
gpt4 key购买 nike

我有表:

Worker (ID, Name)

Box (ID, Name, ID_Worker)

BoxColor (ID, Name)
BoxSize (ID, Name)

Item(ID, ID_box, ID_BoxColor, ID_BoxSize)

所以我们有工作人员创建元素并将它们放入盒子中。为了我的 secret 工作,我改变了话题,从我的 secret 到 ehm boxes ;)

我正在尝试创建包含列的报告:

Worker.Name | BoxSize.Name | BoxColor(id=0) | BoxColor(id=1) | BoxColor(id=2)

Table Box在其他raports中使用,所以这种表格结构不能改变。

例如我想要得到的是:

分组的 Worker Names 和每个 BoxSize,在列中包含每个 Color 计数。例如:

John | X   | 2 | 4 | 0 |
John | XL | 5 | 1 | 0 |
John | XXL | 2 | 0 | 0 |
John | S | 3 | 1 | 0 |
Adam | X | 5 | 4 | 0 |
Adam | XL | 1 | 3 | 0 |
Adam | S | 0 | 1 | 0 |
....

BoxColor 是一张没有太多颜色的表格,因此可以使用不同的子选择对其进行硬编码,例如

(select count(*) from BoxColor where ID = 0)
(select count(*) from BoxColor where ID = 1)
(select count(*) from BoxColor where ID = 2)

我试图做这样的事情,但查询是循环的,它永远不会停止“思考”

select Worker.Name, BoxSize.Name,
(select count(*) from BoxColor as BoxColor2, Box as Box2, Item as Item2
where Box2.ID_Worker = Worker.ID and
Item2.ID_Box = Box2.ID and
Item2.ID_BoxColor = BoxColor2.ID) and
BoxColor.ID = 0 ) as Red,
(select count(*) from BoxColor as BoxColor2, Box as Box2, Item as Item2
where Box2.ID_Worker = Worker.ID and
Item2.ID_Box = Box2.ID and
Item2.ID_BoxColor = BoxColor2.ID) and
BoxColor.ID = 1 ) as Green,
(select count(*) from BoxColor as BoxColor2, Box as Box2, Item as Item2
where Box2.ID_Worker = Worker.ID and
Item2.ID_Box = Box2.ID and
Item2.ID_BoxColor = BoxColor2.ID) and
BoxColor.ID = 2 ) as Blue,
from Worker, BoxSize, Box, Item
where
Item.ID_Worker = Worker.ID and
Item.ID_Box = Box.ID
Item.ID_BoxSize = BoxSize.ID
group by Worker.Name, BoxSize.Name
having Red > 0, Blue > 0, Green > 0
order by 1, 2

最佳答案

也许是这样的:

SELECT
Worker.Name,
BoxSize.Name,
SUM(CASE WHEN BoxColor.id=0 THEN 1 ELSE 0 END) AS BoxColor_0,
SUM(CASE WHEN BoxColor.id=1 THEN 1 ELSE 0 END) AS BoxColor_1,
SUM(CASE WHEN BoxColor.id=2 THEN 1 ELSE 0 END) AS BoxColor_2
FROM
Worker
JOIN Box
ON Worker.ID=Box.ID_Worker
JOIN Item
ON Item.ID_box=Box.ID
JOIN BoxColor
ON BoxColor.ID=Item.ID_BoxColor
JOIN BoxSize
ON BoxSize.ID=Item.ID_BoxSize
GROUP BY
Worker.Name,
BoxSize.Name

关于mysql - 复杂的查询 - 很少有包含分组列的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19265977/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com