我有一个电子商务应用程序,逻辑简化如下:
有7个学院,每个学院有一个座位,有4个学生有兴趣入学。
以下是如何分配席位......
Akbar将在大学入学324,因为这是他的第一选择,没有竞争。现在他已退出比赛了 即使他处于第二位,阿马尔也入围大学162。安东尼也在大学456获得了他的第一选择,学生打电话给#34; shantanu"没有在任何大学录取。
是否有返回预期结果的SQL查询?
drop table college;
create table college (id int not null, primary key (id));
insert into college values (162), (324), (456), (862), (169), (589), (489);
drop table students;
create table students (name varchar(255), marks int, first_pref int, second_pref int,third_pref int);
insert into students values ('shantanu', 67, 162, 324,456);
insert into students values ('amar', 98, 162, 862, 169);
insert into students values ('akbar', 99, 324, 162, 589);
insert into students values ('anthony', 76, 456, 489, 589);
select * from students;
+----------+-------+------------+-------------+------------+
| name | marks | first_pref | second_pref | third_pref |
+----------+-------+------------+-------------+------------+
| shantanu | 67 | 162 | 324 | 456 |
| amar | 98 | 162 | 862 | 169 |
| akbar | 99 | 324 | 162 | 589 |
| anthony | 76 | 456 | 489 | 589 |
+----------+-------+------------+-------------+------------+
4 rows in set (0.00 sec)
select name, marks, ( case
when first_pref=162 then 1
when second_pref = 162 then 2
when third_pref = 162 then 3 else 0
end ) as mypref from students having mypref > 0
order by marks desc;
+----------+-------+--------+
| name | marks | mypref |
+----------+-------+--------+
| akbar | 99 | 2 |
| amar | 98 | 1 |
| shantanu | 67 | 1 |
+----------+-------+--------+
3 rows in set (0.00 sec)
select name, marks, ( case
when first_pref=324 then 1
when second_pref = 324 then 2
when third_pref = 324 then 3 else 0
end ) as mypref from students having mypref > 0
order by marks desc;
+----------+-------+--------+
| name | marks | mypref |
+----------+-------+--------+
| akbar | 99 | 1 |
| shantanu | 67 | 2 |
+----------+-------+--------+
2 rows in set (0.00 sec)
select name, marks, ( case
when first_pref=456 then 1
when second_pref = 456 then 2
when third_pref = 456 then 3 else 0
end ) as mypref from students having mypref > 0
order by marks desc;
+----------+-------+--------+
| name | marks | mypref |
+----------+-------+--------+
| anthony | 76 | 1 |
| shantanu | 67 | 3 |
+----------+-------+--------+
2 rows in set (0.00 sec)
预期的输出是这样的......
Student_name college_id
akbar 324
amar 162
anthony 456
shantanu NULL
答案 0 :(得分:1)
select name,id from students,college, (case
when first_pref,second_pref,third_pref is not null then mypref
(case
first_pref,second_pref,third_pref == null
end)
else null
end)
as mypref;
答案 1 :(得分:0)
要获得case
的学生首选:
select name,
(case when first_pref is not null then first_pref
when second_pref is not null then second_pref
when third_pref is not null then third_pref
else null
end) as mypref
from students;