我有一张包含4张桌子的数据库:预订,酒店,客人和房间。我正在尝试获取我的SQL语句(在Oracle中)以生成每家酒店的平均房价。这是我现在所拥有的:
SELECT HOTEL.H_NAME "HOTEL NAME", ROUND(AVG (R_PRICE), 1) "AVERAGE ROOM PRICE"
FROM ROOM, HOTEL
WHERE HOTEL.H_NAME = 'Shangra_La'
OR HOTEL.H_NAME = 'Hilton'
OR HOTEL.H_NAME = 'Sheraton'
GROUP BY HOTEL.H_NAME
ORDER BY HOTEL.H_NAME;
根据我的想法,该声明将选择'Shangra_la','Hilton'和'Sheraton'中所有房间的酒店名称和平均价格,并按照酒店名称订购,但是当我这样做时,我得到的每个酒店的平均值都是错误的。这是我的输出:
H_NAME AVG. R_PRICE
Hilton 253.5
Shangra_La 253.5
Sheraton 253.5
以下是ROOM的表格数据:
insert into room values
('1','H100','S',220.00);
insert into room values
('2','H100','D',230.00);
insert into room values
('3','H100','F',310.00);
insert into room values
('1','H200','S',260.00);
insert into room values
('2','H200','D',170.00);
insert into room values
('3','H200','S',250.00);
insert into room values
('4','H200','F',180.00);
insert into room values
('5','H200','F',295.00);
insert into room values
('1','H300','D',200.00);
insert into room values
('2','H300','S',420.00);
AND HOTEL:
insert into hotel values
('H100','Sheraton','Melbourne');
insert into hotel values
('H200','Shangra_La','Sydney');
insert into hotel values
('H300','Hilton', 'Perth');
我是否错误地构建了声明?我该怎么做才能解决这个问题?希望我提供了足够的信息。
答案 0 :(得分:2)
您需要将两个表连接在一起:
SELECT HOTEL.H_NAME "HOTEL NAME", ROUND(AVG (R_PRICE), 1) "AVERAGE ROOM PRICE"
FROM ROOM, HOTEL
WHERE HOTEL.H_NAME = 'Shangra_La'
OR HOTEL.H_NAME = 'Hilton'
OR HOTEL.H_NAME = 'Sheraton'
AND HOTEL.R_NUM = ROOM.R_NUM -- Here (guessing at your column names)
GROUP BY HOTEL.H_NAME
ORDER BY HOTEL.H_NAME;
编辑:
SELECT H.H_NAME "HOTEL NAME", ROUND(AVG (R.R_PRICE), 1) "AVERAGE ROOM PRICE"
FROM ROOM R INNER JOIN HOTEL H ON R.HOTEL_NO = H.HOTEL_NO
WHERE H.H_NAME = 'Shangra_La'
OR H.H_NAME = 'Hilton'
OR H.H_NAME = 'Sheraton'
GROUP BY H.H_NAME
ORDER BY H.H_NAME;
否则您看到的平均数将是所有房间的平均值和平均值。价格
答案 1 :(得分:2)
您没有加入条件,因此它采用room
和hotel
的叉积。
SELECT HOTEL.H_NAME "HOTEL NAME", ROUND(AVG (R_PRICE), 1) "AVERAGE ROOM PRICE"
FROM ROOM JOIN HOTEL ON HOTEL.HOTEL_NO = ROOM.HOTEL_NO
WHERE HOTEL.H_NAME = 'Shangra_La'
OR HOTEL.H_NAME = 'Hilton'
OR HOTEL.H_NAME = 'Sheraton'
GROUP BY HOTEL.H_NAME
ORDER BY HOTEL.H_NAME;
答案 2 :(得分:0)
我没有测试过,但你的第一行应该是这样的:
HOTEL.H_NAME "HOTEL NAME", ROUND(AVG (HOTEL.R_PRICE), 1)
我认为你的平均价格高于所有价格 酒店特异性 之一。
答案 3 :(得分:0)
查询缺少一项重要信息:hotel
和room
之间的链接。数据库不知道H100
是酒店;你必须告诉。这称为“连接”(因为您以某种方式加入两个集合)。
将AND ROOM.R_HOTEL_ID = HOTEL.H_ID
添加到WHERE
子句中(您必须使用正确的列名,但您明白了这一点。)