子查询和SUM

时间:2015-11-07 07:56:03

标签: mysql subquery

需要帮助我有一个问题SQL语句,可以检索最大的"总房间成本"在连锁酒店。并使用子查询来确定按酒店分组的总房间成本..我可以做2个查询,但我不断收到错误将它们组合在一起。我的两张桌子。酒店 - 与表hotel_no和hotelname。房间 - 有table room_no,hotel_no,room_type,room_price

到目前为止我已经

SELECT hotelname, SUM(room_price) as Total
FROM hotel, room
WHERE hotel.hotel_no = room.hotel_no
GROUP BY Hotelname

给我酒店名称和每个酒店价格

SELECT SUM(room_price) AS Total 
FROM room 

给我总计

每当我尝试将它们组合在一起时,我都会收到错误消息 例如

SELECT hotel_no, SUM(room_price) AS "Total" 
FROM room
WHERE hotel_no= hotel_no
UNION ALL
SELECT hotel_no, hotelname 
FROM hotel
WHERE hotelname = hotelname
group by hotelname;

请帮助Thx

Sry是一个痛苦但显然它得到了正确的答案,但我错了它必须是来自的一个子查询 在这家酒店的问题,连锁酒店的每家酒店都有不同的房间,酒店想要知道哪个酒店的房间总成本最高

样品

SELECT MAX(SubFromName.NewColumnName)
FROM (SELECT columnName, SUM(columnName) AS ‘NewColumnName’ 
FROM table 
GROUP BY columnName) SubFromName;

希望此链接有效,这是架构数据http://www.sqlfiddle.com/#!9/48429

我最接近但是仍然不对

select hotelname, MAX(room_price), SUM(room_price) AS 'Total Room Cost'
from room,hotel
WHERE hotelname IN (SELECT hotelname FROM hotel 
WHERE hotel.hotel_no = room.hotel_no)
group by hotelname;

不能加入或联合应该像样本如果有人得到我的意思谢谢你提前。我有一个脑死亡的一周。

3 个答案:

答案 0 :(得分:0)

试试这个:

SELECT hotel_no, SUM(room_price) AS Total, "" as hotelname
FROM room
WHERE hotel_no= hotel_no
UNION ALL
SELECT hotel_no, "" AS Total, hotelname as hotelname
FROM hotel
WHERE hotelname = hotelname
group by hotelname;

UNION ALL在两个查询中都应包含相同数量的列。

答案 1 :(得分:0)

Select chain_name, sum(price)
From chain a
Inner join 
(Select a.hotel_no, sum(room_price) as price,         b.chainid
From room a
Inner join hotel b 
On a.hotel_no = b.hotel_no
Group by a.hotel_no) b
On a.Id =b.chainid

按chain_name分组

答案 2 :(得分:0)

只是为了回答自己,这就是我最终的成就

SELECT  hotelname,
(SELECT SUM(room_price) from room where hotel_no = hotel.hotel_no) as TotalRoomCost
from hotel
GROUP BY hotelname

这就是这个

SELECT MAX(Eagle.TotalRoomCost)
FROM (SELECT hotel_no, SUM(room_price) AS 'TotalRoomCost' FROM room GROUP BY hotel_no) Eagle;