Mysql - 选择包含所有日期的房间

时间:2018-06-07 09:40:38

标签: mysql sql database date

大家好,我在这样的桌子上有房间可用:

room_id |          date       
   1    | 2018-06-09 00:00:00 
   1    | 2018-06-10 00:00:00 
   1    | 2018-06-11 00:00:00 
   2    | 2018-06-09 00:00:00 
   2    | 2018-06-11 00:00:00 
   3    | 2018-06-09 00:00:00 
   4    | 2018-06-07 00:00:00 
...

我发送了一系列日期,如果任何房间都有可用的日期我想知道:

SELECT rtd.room_id, CASE WHEN Count(rtd.room_id) < 2 THEN 'no' ELSE 'yes' END
FROM room_type_day as rtd
WHERE 
rtd.date IN ('2018-06-09 00:00:00', '2018-06-10 00:00:00', '2018-06-11 00:00:00')
GROUP BY rtd.room_type_id

但这让我回答:

1  | yes
2  | yes
3  | yes
4  | no

如何找到全天可用的房间?

谢谢。

修改

如果我在“group by”之前添加HAVING(COUNT DISTINCT rtd.date)= 3“,我收到此错误: enter image description here

修改

这对我有用:

SELECT `room_id`
FROM `room_type_day`
WHERE `date` IN ('2018-06-09', '2018-06-10', '2018-06-11')
GROUP BY `room_id`
HAVING COUNT(`room_id`) = 3;

但是如果一个或多个房间可用,我该如何修改此查询,返回“是”,如果没有,则返回“否”?

Thak you

3 个答案:

答案 0 :(得分:2)

使用GROUP BYHAVING子句。

<强>查询

SELECT `room_id`
FROM `room_type_day`
WHERE `date` IN ('2018-06-09', '2018-06-10', '2018-06-11')
GROUP BY `room_id`
HAVING COUNT(`room_id`) = 3;

<强> Find SQL Fiddle here

答案 1 :(得分:0)

您正在按表中未找到的列进行分组。

SELECT 
   A.room_id, 
   IF(A.count=A.count_in_range,'Yes','No') status
FROM 
(SELECT 
   room_id, 
   COUNT(*) count, 
   SUM(IF(date IN ('2018-06-09 00:00:00', '2018-06-10 00:00:00', 
                   '2018-06-11 00:00:00'),1,0)) count_in_range
FROM room_type_day
GROUP BY room_id) A;

请参阅Demo on SQL Fiddle

答案 2 :(得分:0)

尝试这样做并确保'IN'语句中的days_ =天数

    SELECT room_id, CASE WHEN days_=3 THEN 'yes' ELSE 'No' END) as availability
    FROM
    (
      SELECT rtd.room_id, Count(distinct rtd.room_id)  as days_
      FROM room_type_day as rtd
      WHERE rtd.date IN ('2018-06-09 00:00:00', '2018-06-10 00:00:00', '2018-06-11 00:00:00')
      GROUP BY rtd.room_type_id
     ) as sub