我有一个表名学生,有两列name
和status
CREATE TABLE student
(
name varchar(30) , status varchar(30)
);
INSERT INTO student
(name, status)
VALUES
('a','pass'),
('a','fail'),
('a','pass'),
('b','fail'),
('b','fail'),
('b','pass');
查询应显示3列
name pass fail
a 2 1
b 1 2
即。学生的名字对应的数量为no。他们通过的科目和他们失败的科目数量应该显示在结果中。
答案 0 :(得分:6)
select name,
sum(case when status = 'pass' then 1 else 0 end) as sumPass,
sum(case when status = 'fail' then 1 else 0 end) as sumFail
From student
group by name
答案 1 :(得分:2)
你可以在MYSQL中使用它:(假设你使用的是MYSQL,不可移植到 Oracle, SQL Server
)
select name,
sum(status = 'pass') as Pass,
sum(status = 'fail') as Fail
From student
group by name
;
| NAME | PASS | FAIL |
----------------------------
| a | 2 | 1 |
| b | 1 | 2 |