我有桌子:
Worker (ID, Name)
Box (ID, Name, ID_Worker)
BoxColor (ID, Name)
BoxSize (ID, Name)
Item(ID, ID_box, ID_BoxColor, ID_BoxSize)
所以我们有工人创造物品并将它们放在他们的盒子里。为了我的秘密工作,我改变了话题,从我的秘密话题转到了 ehm 盒子;)
我正在尝试创建具有列的报告:
Worker.Name | BoxSize.Name | BoxColor(id=0) | BoxColor(id=1) | BoxColor(id=2)
表格框用于其他报告,因此这种表格结构可以改变。
例如,我想要得到的是:
分组的工人名称和每个 BoxSize,在每个颜色计数的列中都有。例如:
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