MySQL - 如何查询此输出?

时间:2015-07-03 18:09:13

标签: mysql sql

我有这样的数据:

+-------+--------+---------------------+
| 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 ="????")

2 个答案:

答案 0 :(得分:0)

要获取类似的结果集(从SQL SELECT语句返回)语句,并为每个名称值指定一个单独的列,您绝对必须在SELECT列表中包含要返回的每个列的表达式。

语句运行时,必须指定从SELECT语句返回的列的数量,类型和名称。当语句运行时,不能动态地改变它。

要考虑的几个选项:

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

  • 使用单独的查询来检索name值的不同列表,并使用其中的return来动态构建第二个语句(就像您当前使用的那个。)

    < / LI>

答案 1 :(得分:0)

您想要的是数据透视表。

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了解详情。

希望这会对你有所帮助。