Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

count row values as column name mysql

Tags:

select

mysql

row

I have table 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);

Which look like:

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

I want to get result below:

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

But I have no idea how to group designer_id then count distinct status and each into columns like above.

like image 506
xCiCi Avatar asked Mar 24 '14 04:03

xCiCi


1 Answers

Try this

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

As Jack said It's simply workig with this

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

like image 90
Vignesh Kumar A Avatar answered Oct 06 '22 01:10

Vignesh Kumar A