MySQL从子查询行到列

标签 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 |
+------------+-----------+-------+--------+

谢谢。

最佳答案

您需要一个条件聚合来进行透视:

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/

相关文章:

sql - 使用 Entity Framework 时锁定记录进行编辑的最佳实践

sql - 按列排序表,但如果为0,则忽略-SQLite

mysql - 增量触发器更新mysql

mysql - 找不到“./mysql/user.MYD”(错误代码 : 13 - Permission denied)

mysql - 如何根据另一列的最大值获取一列的多个值?

php - 如何让php添加utf8字符

c# - 将 SQL 表读入 C# DataTable

sql - 谷歌是否更改/更新了与 Cloud SQL 的 vm ssl 连接相关的内容?

sql - Oracle 12c 解析函数

c# - SQL查询基于空日期条件和另一个字段的特定值