2014-05-13 53 views
0

我創建了一個旅館的數據庫,我已經建立了SQL Server中的所有表,現在我正在嘗試編寫正弦查詢。我想獲得帶有免費座位的房間號碼。如何寫一個查詢獲得免費座位在旅館

我有表Students,Contracts,Rooms

Contracts具有柱Student它引用在StudentsContractsStudentId具有引用Rooms表的RoomIdRoomRoomId是房間號碼。

Room也有一列NumberSeats這是一個房間的座位總數。所以我認爲這足以理解我的問題並撰寫查詢。

我想獲得帶有空閒座位的房間號碼。我不知道如何實現這個,我是SQL中的新成員,所以我所嘗試的一切都沒有成功。你有什麼想法?謝謝。

+0

你能與您的查詢(ES),即使他們無法正常工作編輯您的問題嗎? –

+0

@Lesya我可以做一個查詢,讓一些人住在某個房間裏'SELECT Count(*)FROM Students WHERE StudentId IN(SELECT Student from Contracts WHERE Room = 711)'這就是全部。我試圖解決這個問題,但我無法得到如何爲每個房間做好準備 – user3061137

+0

如果你將架構和查詢發佈到[SQL Fiddle](http:// sqlfiddle.com/)。 –

回答

0

如果您的合同表中提供了由其ID提及的所有學生,則只需引用合同和房間即可提取數據。您可以通過連接兩個表,計算每間客房的學生人數和增加的條件爲having子句嘗試:

SELECT b.RoomId, 
    b.NumberSeats, 
    COUNT(a.Student) 
FROM Rooms b 
LEFT JOIN Contracts a 
ON a.Room=b.RoomId 
GROUP BY b.RoomId, 
    b.NumberSeats 
HAVING b.NumberSeats>COUNT(a.Student); 
+0

謝謝!這幫助了很多,並且工作正常!需要深入瞭解彙總功能 – user3061137

+0

歡迎您 –

0

我準備這個例子給你。 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  | 
+0

謝謝您的回答。我知道我需要使用聚合函數,謝謝 – user3061137

相關問題