我準備這個例子給你。 DDL +查詢 - >
create table student
(id number,
name varchar2(100));
create table room
(id number,
name varchar2(100));
create table contract
(student_id number,
room_id number);
create table number_seats
(room_id number,
number_seats number);
insert into student values(1, 'Jon');
insert into student values(2, 'George');
insert into student values(3, 'Ian');
insert into student values(4, 'Alex');
insert into student values(5, 'Mary');
insert into room values(1, 'room1');
insert into room values(2, 'room2');
insert into room values(3, 'room3');
insert into room values(4, 'room4');
insert into room values(5, 'room5');
insert into number_seats values(1, 1);
insert into number_seats values(2, 2);
insert into number_seats values(3, 3);
insert into number_seats values(4, 2);
insert into number_seats values(5, 1);
insert into contract values(1, 1);
insert into contract values(2, 2);
insert into contract values(3, 3);
insert into contract values(4, 4);
insert into contract values(5, 4);
select * from room;
select * from student;
select * from contract;
select * from number_seats;
select cont.room_id, num_seats.number_seats - count(*)
from student st
join contract cont on st.id=cont.student_id
join room ro on ro.id=cont.room_id
join number_seats num_seats on num_seats.room_id=ro.id
group by cont.room_id, num_seats.number_seats
union
select ro.id, num_seats.number_seats
from room ro left join contract co on ro.id=co.room_id
join number_seats num_seats on num_seats.room_id=ro.id
where co.room_id is null
order by 1;
結果是
|roomNumber|freeSeats|
| 1 | 0 |
| 2 | 1 |
| 3 | 2 |
| 4 | 0 |
| 5 | 1 |
你能與您的查詢(ES),即使他們無法正常工作編輯您的問題嗎? –
@Lesya我可以做一個查詢,讓一些人住在某個房間裏'SELECT Count(*)FROM Students WHERE StudentId IN(SELECT Student from Contracts WHERE Room = 711)'這就是全部。我試圖解決這個問題,但我無法得到如何爲每個房間做好準備 – user3061137
如果你將架構和查詢發佈到[SQL Fiddle](http:// sqlfiddle.com/)。 –