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

时间:2014-01-24 09:22:42

标签: mysql sql select count group-by

基本上我需要列中的不同值通过Query

作为列名

示例如下

  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'用作列名,按日期分组

3 个答案:

答案 0 :(得分:2)

试试这个:

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

选中此SQL FIDDLE DEMO

<强>输出

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

答案 1 :(得分:0)

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

SELECT
  date,
  COUNT(IF(status = 'p', status, NULL)) AS p,
  COUNT(IF(status = 'a', status, NULL)) AS a,
  COUNT(IF(status = 'hd', status, NULL)) AS hd
FROM
  table
GROUP BY
  date;

你也可以尝试自动化这个逻辑,看一下这个链接 - Dynamic pivot tables (transform rows to columns)

答案 2 :(得分: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

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