SQL数据库查询显示额外日期

时间:2013-09-23 12:01:18

标签: sql postgresql postgresql-9.1

我正在用postgresql 9.1创建一个数据库 给出表格:

CREATE TABLE rooms(
    room_number int,
    property_id int,
    type character varying,
    PRIMARY KEY (room_number, property_id)
);
Insert into rooms values (1,1,double),(2,1,double),(3,1,triple)

CREATE TABLE reservations(
    reservation_ID int,
    property_id int,
    arrival date,
    departure date,
    room_num int,
    PRIMARY KEY(reservation_ID,property_id)
    FOREIGN KEY (room_number, property_id)
);

INSERT INTO orders VALUES (1,1,2013-9-27,2013-9-30,1), 
                          (2,1,2013-9-27,2013-9-28,2),
                          (3,1,2013-9-29,2013-9-30,3);

我想提供2个日期并检查两者之间的可用性。所以在第一栏应该是apear:

  1. 给定和

  2. 之间的所有日期
  3. 显示可用性的每种类型房间的额外一列。

  4. 所以我的结果,鉴于2013-9-27& 2013-9-30作为输入,必须是这样的:

    enter image description here

1 个答案:

答案 0 :(得分:0)

我认为最好的解决方案是使用generate_series()和crosstab()来创建动态表。此外,您可以使用从CTE到数据表的左连接,以便获得更好的信息。类似的东西:

 WITH daterange as (
      SELECT s::date as day FROM generate_series(?, ?, '1 day')
 )
 SELECT dr.day, sum(case when r.type = 'double' then r.qty else 0) as room_double,
        sum(case when r.type = 'triple' then r.qty else 0) as room_triple....
 );

但请注意,交叉表会使第二个查询更容易。