我需要有关如何编写 SQL 查询以按照我想要的格式输出数据的帮助。
我有这个查询返回以下输出,
select d.date, d.meal, sum(swipe)
from (
select date, meal, card_id, count(card_id) as swipe
from history where date >= DATE_SUB(NOW(),INTERVAL 2 DAY)
group by card_id, meal, date
) as d
group by d.date, d.meal
当前输出:
+------------+-----------+------------+
| Date | Meal | sum(swipe) |
+------------+-----------+------------+
| 2015-10-27 | Breakfast | 138 |
| 2015-10-27 | Dinner | 205 |
| 2015-10-27 | Lunch | 247 |
| 2015-10-26 | Breakfast | 137 |
| 2015-10-26 | Dinner | 190 |
| 2015-10-26 | Lunch | 231 |
+------------+-----------+------------+
是否可以从上面的输出查询返回类似这样的内容:
+------------+-----------+-------+--------+
| Date | Breakfast | Lunch | Dinner |
+------------+-----------+-------+--------+
| 2015-10-26 | 137 | 231 | 190 |
| 2015-10-27 | 138 | 247 | 205 |
+------------+-----------+-------+--------+
谢谢。
最佳答案
您需要一个条件聚合来进行透视:
select d.date,
sum(case when meal = 'Breakfast' then swipe else 0 end) as Breakfast,
sum(case when meal = 'Lunch' then swipe else 0 end) as Lunch,
sum(case when meal = 'Dinner' then swipe else 0 end) as Dinner
from (
select date, meal, card_id, count(card_id) as swipe
from history where date >= DATE_SUB(NOW(),INTERVAL 2 DAY)
group by card_id, meal, date
) as d
group by d.date
顺便说一句,这个查询可能可以简化为:
select d.date,
sum(case when meal = 'Breakfast' then 1 else 0 end) as Breakfast,
sum(case when meal = 'Lunch' then 1 else 0 end) as Lunch,
sum(case when meal = 'Dinner' then 1 else 0 end) as Dinner
from history
where date >= DATE_SUB(NOW(),INTERVAL 2 DAY)
group by d.datle
关于MySQL从子查询行到列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33402180/