最初在Query based on column values in row问。
我在http://sqlfiddle.com/#!9/362f1cd/2有sqlfiddle。
我有一个客户表,其中包含诸如 id,名称,手机,电子邮件之类的列,以及一个每周摘要表,其中包含诸如 id,customerid,day_of_week,type_of_food,name_of_food 。 type_of_food列的值包括早餐,午餐,晚餐,蛋白质,小吃等(可以是n种)。
我需要的是
这样的报告客户名,手机,电子邮件,早餐,午餐,早餐2,小吃1,小吃2 ...(最多可以为n)
Acc1,Mob1,Email1,name_of_breakfast_food,name_of_lunch_food,name_of_dinner_food,... Acc2,Mob2,Email2,name_of_breakfast_food,name_of_lunch_food,name_of_dinner_food,...
请记住,同一天可以有多种食物,例如一个帐户可以享用2份早餐和3种小吃。
请注意,问题@ MySQL pivot row into dynamic number of columns仅有助于获取元素(type_of_food)的数量,而如果有2个条目(甚至是同一类型),则我需要将它们分开(以及name_of_lunch_food中的值) )。
编辑:基于sqlfiddle添加预期结果
姓名,手机,电子邮件,日期,早餐,快餐,午餐,快餐1,晚餐,快餐2
acc1、1234,acc1 @ yopmail.com,星期一,鸡蛋,薯条,米饭,苹果,面包,豆腐
acc1,1234,acc1 @ yopmail.com,星期二,面包,-,-,-,牛奶,-
acc2、2345,acc2 @ yopmail.com,星期一,鸡蛋,薯条,米饭,苹果,面包,-
acc2,2345,acc2@yopmail.com,星期二,-,凝乳,面包,-,牛奶,-
答案 0 :(得分:1)
我会使用group_concat
函数:
SELECT c.id, c.name, c.email, w.day_of_week,
group_concat(CASE WHEN w.type_of_food = 'Breakfast' THEN w.name_of_food END ) As breakfests,
group_concat(CASE WHEN w.type_of_food = 'Snack' THEN w.name_of_food END ) As Snacks,
group_concat(CASE WHEN w.type_of_food = 'Lunch' THEN w.name_of_food END ) As Lunches,
group_concat(CASE WHEN w.type_of_food = 'Dinner' THEN w.name_of_food END ) As Dinners
FROM customer c
JOIN weekly_report w ON c.id = w.customerid
GROUP BY c.id, c.name, c.email, w.day_of_week
演示:http://sqlfiddle.com/#!9/362f1cd/3
| id | name | email | day_of_week | breakfests | Snacks | Lunches | Dinners |
|----|------|------------------|-------------|------------|------------------|---------|---------|
| 1 | acc1 | acc1@yopmail.com | Mon | Eggs | Fries,Apple,Curd | Rice | Bread |
| 1 | acc1 | acc1@yopmail.com | Tue | Bread | (null) | (null) | Milk |
| 2 | acc2 | acc2@yopmail.com | Mon | Eggs | Fries,Apple | Rice | Bread |
| 2 | acc2 | acc2@yopmail.com | Tue | (null) | Curd | Bread | Milk |