缺少记录的SQLite中的数据透视

时间:2018-07-25 23:14:41

标签: sql sqlite

我想使用SQLite根据两个表(学生和成绩)输出记录表。输出中的数据是针对给定班级的给定学生记录的最高分数。我查看了SO #1237068,但是对于在学生表中有记录但在标记表中是记录的学生,我的查询必须输出零。这就是我想为学生“亚历克斯”看到的东西:

studid      name        subjid_3    subjid_4    subjid_5
----------  ----------  ----------  ----------  ----------
A1          Raam        55          60          70
B1          Vivek       60          80          0
C1          Alex        0           0           0

我用于创建表和发出查询的(破碎的)SQL在这里;这不会为Alex打印记录。如何修改select语句以为Alex编写记录?

create table marks (studid, subjid, marks);
create table students (studid, name);

insert into marks values('A1', 3, 50);
insert into marks values('A1', 3, 55);
insert into marks values('A1', 4, 60);
insert into marks values('A1', 5, 70);
insert into marks values('B1', 3, 60);
insert into marks values('B1', 4, 80);

insert into students values('A1', 'Raam');
insert into students values('B1', 'Vivek');
insert into students values('C1', 'Alex');

select si.studid, si.name,
max(case when gd.subjid = 3 then gd.marks else 0 end) subjid_3,
max(case when gd.subjid = 4 then gd.marks else 0 end) subjid_4,
max(case when gd.subjid = 5 then gd.marks else 0 end) subjid_5
from students si
join marks gd
on gd.studid = si.studid
group by si.studid, si.name;

1 个答案:

答案 0 :(得分:0)

这是带有left join的条件聚合:

select s.studid,
       max(case when m.subjid = 3 then mark else 0 end) as subjid_3,
       max(case when m.subjid = 4 then mark else 0 end) as subjid_4,
       max(case when m.subjid = 5 then mark else 0 end) as subjid_5
from students s left join
     marks m
     on s.studid = m.studid
group by s.studid;