MySQL从子查询中排到列

时间:2015-10-28 21:47:07

标签: mysql sql

我需要有关如何编写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 |
+------------+-----------+-------+--------+

谢谢。

1 个答案:

答案 0 :(得分:1)

您需要一个条件聚合来转动:

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