gpt4 book ai didi

mysql - 将行值计为列名 mysql

转载 作者:可可西里 更新时间:2023-11-01 06:41:06 25 4
gpt4 key购买 nike

我有表 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 并将每个列放入如上所示的列中。

最佳答案

试试这个

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

关于mysql - 将行值计为列名 mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22601392/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com