将行值计为列名mysql

时间:2014-03-24 04:58:16

标签: mysql select row

我有表user_completed

CREATE TABLE IF NOT EXISTS `user_completed` (
  `rowId` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `designer_id` int(10) unsigned NOT NULL,
  `status` varchar(54) DEFAULT NULL,
  PRIMARY KEY (`rowId`),
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;


INSERT INTO `user_completed` (`rowId`, `designer_id`, `status`) VALUES
(1, 1, accept),
(2, 1, reject),
(3, 1, accept),
(4, 1, reject),
(5, 1, overtime),
(6, 2, accept)
(7, 2, accept)
(8, 3, accept)
(9, 2, reject);

看起来像:

rowId   designer_id    status 
1           1          accept
2           1          reject
3           1          accept
4           1          reject
5           1          overtime
6           2          accept
7           2          accept
8           3          accept
9           2          reject

我想得到以下结果:

designer_id   accept   overtime   reject
1             2        1          2
2             2        0          1
3             1        0          0

但我不知道如何对designer_id进行分组,然后对不同的status进行分组,并将每个分组为上述列。

3 个答案:

答案 0 :(得分:10)

试试这个

SELECT  designer_id,
    SUM(IF(status = 'accept',1,0)) as 'Accept',
    SUM(IF(status = 'reject',1,0)) as 'Reject',
    SUM(IF(status = 'overtime',1,0)) as 'Overtime'
FROM 
    user_completed
Group By designer_id

<强> Fiddle Demo

正如Jack所说,这简直就是这个

SELECT  designer_id,
    SUM(status = 'accept') as 'Accept',
    SUM(status = 'reject') as 'Reject',
    SUM(status = 'overtime') as 'Overtime'
FROM 
    user_completed
Group By designer_id

<强> Fiddle Demo

答案 1 :(得分:1)

试试这个它会起作用

select designer_id, 
count(case status  when 'accept'then 1 else null end)as accept,
count(case status when 'reject'then 1 else null end)as reject,
count(case status when 'overtime'then 1 else null end)as overtime
from user_completed group by designer_id

答案 2 :(得分:0)

如果你不知道你有多少个status,那么你可以查看这个链接以寻求解决方案

Mysql query to dynamically convert rows to columns

例如,您可以使用以下内容

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
   CONCAT(
     'SUM(IF(`status` = "', `status`, '",1,0)) AS ', `status`)
  ) INTO @sql
FROM user_completed;

SET @sql = CONCAT('SELECT  designer_id, ', @sql, ' 
              FROM    user_completed
              GROUP  BY  designer_id');
SELECT @sql;
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;