SQL查询我有一个表名学生,有两列名称和状态

时间:2013-02-01 13:31:11

标签: sql

我有一个表名学生,有两列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

即。学生的名字对应的数量为no。他们通过的科目和他们失败的科目数量应该显示在结果中。

2 个答案:

答案 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

sqlFiddle

答案 1 :(得分:2)

你可以在MYSQL中使用它:(假设你使用的是MYSQL,不可移植到 Oracle, SQL Server

MYSQL DEMO

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 |