如何选择同一人预订的房间的总价

时间:2019-04-18 16:17:23

标签: sql oracle

我创建了一个表格:

Create table rooms
(
roomNo int not null,
hotelNo int not null,
hotelName varchar (40) not null,
roomType varchar (40)
default 'standard' check (roomType in ('single', 'double', 'master', 
'standard', 'president')),
price decimal (8,2) check (price>=0 and price<=99999),
guestNo int null
)

roomNohotelNo是主键,guestNo是外键。

该表填充了以下值:

(101, 123456, 'Home','standard',300, 54321)
(101, 654321, 'Ibis','standard',300, Null)
(101, 987654, 'Hiton','president',15000, null)
(222, 987654, 'Hiton','standard',300, 12345)
(321, 987654, 'Hiton','master',1000, 11111)
(333, 123456, 'Home','single',100, null)
(333, 987654, 'Hiton','standard',300, 12345)
(567, 654321, 'Ibis','standard',300, null)
(888, 654321, 'Ibis','single' ,100, null)
(999, 654321, 'Ibis','double' ,200, null) 

如何回答“选择同一人预订的房间的总价”这个问题?

我希望总价为600,但根据此查询,我得到1900:

select sum(price)
from rooms r inner join guests g
on r.guestNo = g.guestNo and g.guestName = g.guestName

1 个答案:

答案 0 :(得分:0)

如果您想要每个人的总价,则需要按该值分组:

select g.guestNo, sum(r.price)
from rooms r inner join guests g
on r.guestNo = g.guestNo
group by g.guestNo
order by g.guestNo;

   GUESTNO SUM(R.PRICE)
---------- ------------
     11111         1000
     12345          600
     54321          300

如果您只对进入一个以上房间的客人感兴趣,则可以添加一个having子句以检查有多少个房间:

select g.guestNo, sum(r.price)
from rooms r inner join guests g
on r.guestNo = g.guestNo
group by g.guestNo
having count(r.roomNo) > 1
order by g.guestNo;

   GUESTNO SUM(R.PRICE)
---------- ------------
     12345          600

Read more

您的数据模型似乎很奇怪;在房间里记录一个特定的客人似乎很奇怪。也许您应该从中删除guestNo,并使用另一个表将房间链接到客人,也许是在日期范围内。价格可能也会有所不同,因此可能需要在预订表中,或者在另一个表中(以考虑季节性定价等)?