Mysql - 基于数学运算和SUM()函数对结果进行分组

时间:2010-04-17 05:04:21

标签: mysql group-by aggregate

我有以下两张桌子......

表:room_type

 type_id    type_name   no_of_rooms     max_guests  rate    
  1          Type 1         15               2      1254    
  2          Type 2         10               1      3025

表:预订

reservation_id  start_date  end_date    room_type   booked_rooms    
       1        2010-04-12  2010-04-15      1            8 
       2        2010-04-12  2010-04-15      1            2 

现在......我有这个查询

SELECT type_id, type_name
FROM room_type
WHERE id NOT IN (SELECT room_type
             FROM reservation
             WHERE start_date >= '$start_date'
             AND   end_date <= '$end_date')

查询的作用是选择在开始日期和结束日期之间未预订的房间。

此外,正如您在预订表中所看到的,我们还有'两个日期之间预订的房间数'因素...

我需要在查询中添加“两个日期之间预订的房间”因素...

查询应该返回两个日期之间至少有一个房间空闲的房间类型。

我计算出逻辑,但不能将其表示为查询......!你会怎么做......?

感谢您的建议..!

1 个答案:

答案 0 :(得分:1)

您的结果可能会在此

中获得
 SELECT a.type_id, a.type_name, a.no_of_rooms, (

SELECT SUM( booked_rooms )
FROM reservation
WHERE room_type = a.type_id
AND start_date >= '2010-04-12'
AND end_date <= '2010-04-15'
) AS booked_rooms, (
a.no_of_rooms - (
SELECT SUM( booked_rooms )
FROM reservation
WHERE room_type = a.type_id
AND start_date >= '2010-04-12'
AND end_date <= '2010-04-15' )
) AS freerooms
FROM room_type AS a
LEFT JOIN reservation AS b ON a.type_id = b.room_type
GROUP BY a.type_id
ORDER BY a.type_id