复杂查询 - 少数具有分组列的表

时间:2013-10-09 07:45:30

标签: mysql sql

我有桌子:

Worker (ID, Name)

Box (ID, Name, ID_Worker)

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

Item(ID, ID_box, ID_BoxColor, ID_BoxSize)

所以我们有工人创造物品并将它们放在盒子里。 为了我的秘密工作,我改变了主题,从我的秘密改为ehm盒子;)

我正在尝试创建具有列的raport:

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

Table Box用于其他raports,因此这种表结构可以改变。

我想要得到的是:

分组的工作人员姓名和每个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

1 个答案:

答案 0 :(得分:3)

也许是这样的:

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