如何在SQL中转动行?

时间:2017-02-26 12:46:58

标签: mysql

我有一张桌子:

   date       Name
2017-02-21    Mark
2017-02-21    Peter
2017-02-21    John
2017-02-22    Mark
2017-02-22    Mark
2017-02-22    Mark
2017-02-22    Peter

我想要以下输出:

    date    Mark  John  Peter
2017-02-21   1      1    1
2017-02-22   3      0    1

我如何在MySQL中实现这一目标?

3 个答案:

答案 0 :(得分:1)

您可以使用聚合来透视数据,如下所示:

select date,
    sum(Name = 'Mark') Mark,
    sum(Name = 'John') John,
    sum(Name = 'Peter') Peter
from your_table
group by date;

它使用MySQL评估true为1而false为0的事实。

SQLFiddle

答案 1 :(得分:1)

使用'FIELD()'

select 
sum(field(name,'mark')) as mark,
sum(field(name,'peter')) as peter,
sum(field(name,'john')) as john 
from table_name group by date;

答案 2 :(得分:0)

这不是您想要的,但您可以使用GROUP BY对结果进行分组,然后计算名称,如下所示:

SELECT *,
    COUNT(name) as how_many
FROM your_table
GROUP BY date, name

SQL Fiddle