MySQL查询在日期范围内每个日期返回一列?

时间:2014-12-29 17:18:49

标签: mysql sql date date-range

让我解释一下我所拥有的以及我想要实现的目标。 我有这样的表格。

假设我有表A:预订

RoomNum     ArrivalDate    DepartureDate
101         2014-12-01     2014-12-03
102         2014-12-02     2014-12-03
103         2014-12-03     2014-12-04
101         2014-12-05     2014-12-06

预期结果应如下所示:

RoomNum        Des-01    Des-02    Des-03    Des-04    Des-05    Des-06
101              1         1         1         0         1         1
102              0         1         1         0         0         0
103              0         1         1         0         1         1              

非常感谢任何想法。

提前致谢

1 个答案:

答案 0 :(得分:0)

您有一个选项,虽然它可能不是高效或动态的,但是使用SUM()函数。在那里,您可以包含案例陈述。

在这种情况下,我写了一个案例陈述,检查当前日期是否在房间的到达和离开日期之间。

SELECT roomnum,
  SUM(CASE WHEN '2014-12-01' BETWEEN arrivalDate AND departureDate THEN 1 ELSE 0 END) AS 'Dec-01',
  SUM(CASE WHEN '2014-12-02' BETWEEN arrivalDate AND departureDate THEN 1 ELSE 0 END) AS 'Dec-02',
  SUM(CASE WHEN '2014-12-03' BETWEEN arrivalDate AND departureDate THEN 1 ELSE 0 END) AS 'Dec-03',
  SUM(CASE WHEN '2014-12-04' BETWEEN arrivalDate AND departureDate THEN 1 ELSE 0 END) AS 'Dec-04',
  SUM(CASE WHEN '2014-12-05' BETWEEN arrivalDate AND departureDate THEN 1 ELSE 0 END) AS 'Dec-05',
  SUM(CASE WHEN '2014-12-06' BETWEEN arrivalDate AND departureDate THEN 1 ELSE 0 END) AS 'Dec-06'
FROM booking
GROUP BY roomnum;

这是SQL Fiddle