我有三张桌子:indi(个人),consump(consump)和manu(制造商)
我想按年龄类别(我有实际年龄)对个人进行分组,并显示制造商消耗的总量。
这样的事情:
Age Category | Manufacturer | Total Volume Consumed
15 - 24 | Coca Cola | 10ML
| Pepsi | 25 ML
现在按照这个例子(How to group number of users by age bands in mysql),我创建了年龄段,如下所示:
SELECT
CASE
WHEN age >=15 AND age <=24 THEN '15-24'
WHEN age >=25 AND age <=34 THEN '25-34'
WHEN age >=35 AND age <=44 THEN '35-44'
WHEN age >=45 AND age <=54 THEN '45-54'
WHEN age >=55 AND age <=66 THEN '54-64'
WHEN age >=65 THEN '65+'
END AS ageband
链接表的密钥为id
和indi
表的consump
以及code
和consump
表的manu
。现在,多个代码附加到一个制造商,因为制造商生产多种类型的饮料。
因此where
子句将包含以下内容:
indi.id = consump.id AND consump.code = manu.code
所以我的思考过程如下(我确实认识到我需要包含case语句,但我不知道我把它放在哪里 - 作为子查询的某个地方?)
SELECT age, manufacturer, SUM(volume) as 'Total Volume Consumed'
FROM indi, consump, manu
WHERE indi.id = consump.id AND consump.code = manu.code
GROUP BY ageband