2

我有一个表名 student 有两列namestatus

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

即学生的姓名对应于哪个计数。他们通过的科目和他们未通过的科目数应显示在结果中。

4

2 回答 2

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

sqlFiddle

于 2013-02-01T13:33:37.337 回答
2

您可以简单地在 MYSQL 中使用它:(假设您使用的是 MYSQL,不能移植到 Oracle, SQL Server

MYSQL 演示

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 |
于 2013-02-01T13:45:18.463 回答