【问题标题】:MySQL - How can I make a query for this output?MySQL - 如何查询此输出?
【发布时间】:2015-07-03 18:09:13
【问题描述】:

我有这样的数据:

+-------+--------+---------------------+
| name  | status | date                |
+-------+--------+---------------------+
| Peter | 100    | 2015-06-20 12:12:00 |
| Peter | 100    | 2015-06-20 15:12:00 |
| James | 100    | 2015-06-20 10:12:00 |
| James | 200    | 2015-06-20 14:12:00 |
| James | 100    | 2015-06-21 06:12:00 |
| James | 100    | 2015-06-21 09:12:00 |
| Peter | 200    | 2015-06-21 13:12:00 |
| Peter | 100    | 2015-06-21 14:12:00 |

我想要这样的输出:

+----------+-------+-------+-------+
| date     | Peter | James | Total |
+----------+-------+-------+-------+
| 20150620 |     2 |     2 |     4 |
| 20150621 |     2 |     2 |     4 |
+----------+-------+-------+-------+

我使用下面的select 语句:

select DATE_FORMAT(date, "%Y%m%d") as date,
SUM(IF(name = "Peter", 1,0)) AS "Peter",
SUM(IF(name = "James", 1,0)) AS "James", 
SUM(IF(name != "0", 1,0)) AS "Total" 
from test group by DAYOFMONTH (date);

但是,如果我有很多名称值,我该怎么办?我不能把所有的名字都放在 select state in SUM(IF name ="????").

【问题讨论】:

标签: mysql sql


【解决方案1】:

要获得这样的结果集(从 SQL SELECT 语句返回)语句,每个名称值都有一个单独的列,您绝对必须在要返回的每一列的 SELECT 列表中包含一个表达式。

SELECT 语句返回的列的数量、类型和名称必须在语句运行时指定。语句运行时不能动态更改。

需要考虑的几个选项:

  • 如果您确实需要在单个查询中使用任意数量的名称值进行动态处理,请考虑将其作为单独的行返回,并在客户端处理数据透视。

  • 使用单独的查询来检索 name 值的不同列表,并使用从该列表的返回来动态构建第二条语句(就像您当前使用的那样。)

【讨论】:

  • 非常感谢 spencer7593,
【解决方案2】:

你想要的是一个数据透视表。

MySQL 没有内置的数据透视表构造实用程序,但您可以使用准备好的语句手动完成:

-- Initialize a variable to store the query string
set @sql = null;
-- Build the query string for each grouped ('name') column and store it
-- into the @sql variable
select group_concat(distinct
                    concat("sum(case when name = '", name, "' then 1 
                                else 0 
                                end) as `", name, "`"
                          )
                   separator ', ')
into @sql
from test;
-- Complete the query string and store it in the @sql variable
set @sql = concat("select date_format(`date`, '%Y%m%d') as `dt`", @sql, " from test group by date(`dt`)");
-- Create a prepared statement and execute it
prepare stmt from @sql;
execute stmt;
-- When you're done, deallocate the prepared statement
deallocate prepare stmt;

Here's a working example in SQLfiddle.

查看this question and its answers了解更多信息。

希望对你有所帮助。

【讨论】:

  • 非常感谢巴兰卡。
  • @Onthemoon 如果您觉得这个答案有用,请点赞,或者,如果它解决了旅游问题,请接受它
猜你喜欢
  • 2015-11-15
  • 2012-01-14
  • 2019-01-21
  • 2016-02-16
  • 1970-01-01
  • 1970-01-01
  • 2013-10-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多