按两列分组,并在MYSQL中使用不同的值作为列名

按两列分组,并在MYSQL中使用不同的值作为列名,mysql,sql,select,count,group-by,Mysql,Sql,Select,Count,Group By,基本上,我需要通过查询将列中的不同值作为列名 下面是一个例子 id status userId date ------------------------ 1 p u12 01/01/2014 2 p u13 01/01/2014 3 a u14 01/01/2014 4 hd u15 01/01/2014 5 a u16 01/01/2014 6 p u12 01/

基本上,我需要通过查询将列中的不同值作为列名

下面是一个例子

  id status  userId  date
  ------------------------
  1   p      u12  01/01/2014
  2   p      u13  01/01/2014
  3   a      u14  01/01/2014
  4   hd     u15  01/01/2014
  5   a      u16  01/01/2014
  6   p      u12  01/02/2014
  7   a      u13  01/02/2014
  8   p      u14  01/02/2014
输出

 date        p  a  hd
 ------------------------
 01/01/2014  2  2   1
 02/01/2014  2  1   0
状态“p”、“a”、“hd”用作列名,并按日期分组

SELECT a.date, SUM(a.status='p') AS p, SUM(a.status='a') AS a, 
       SUM(a.status='hd') AS hd
FROM tableA a
GROUP BY a.date
检查这个

输出

|                           DATE | P | A | HD |
|--------------------------------|---|---|----|
| January, 01 2014 00:00:00+0000 | 2 | 2 |  1 |
| January, 02 2014 00:00:00+0000 | 2 | 1 |  0 |

尝试此查询,但它会强制您了解所有可能的状态(结果字段名称)-

您还可以尝试自动执行此逻辑,请查看此链接-。

此SQL经过测试

    select p.date1,P.p,A.a,case when HD.hd is null then 0 else HD.hd end hd from (select COUNT(status1) p,date1 from tbl1 where status1 ='p' 
group by date1) as P LEFT JOIN (select COUNT(status1) a,date1 from tbl1 where status1 ='a' 
group by date1) as A on P.date1 = A.date1 LEFT JOIN (select COUNT(status1) hd,date1 from tbl1 where status1 ='hd' 
group by date1) as HD on A.date1 = HD.date1

只需根据需要更改表名或列名。

您的问题不清楚,无法理解。请说明您的问题是什么?你卡在哪里了。应该是count而不是sum?@DanielRobertus它会计算记录的。内部条件将返回1或0。所以我用总和代替了计数
    select p.date1,P.p,A.a,case when HD.hd is null then 0 else HD.hd end hd from (select COUNT(status1) p,date1 from tbl1 where status1 ='p' 
group by date1) as P LEFT JOIN (select COUNT(status1) a,date1 from tbl1 where status1 ='a' 
group by date1) as A on P.date1 = A.date1 LEFT JOIN (select COUNT(status1) hd,date1 from tbl1 where status1 ='hd' 
group by date1) as HD on A.date1 = HD.date1