2

表中有每天酒店的配额。如何获得酒店每天可用的天数?

q_id    q_hotel q_date  q_value
1   1   2013-02-01  1
2   1   2013-02-02  1
3   1   2013-02-03  1
4   1   2013-02-04  0
5   1   2013-02-05  2
6   1   2013-02-06  3
7   1   2013-02-07  3
8   1   2013-02-08  2
9   1   2013-02-09  0
10  1   2013-02-10  0
11  1   2013-02-11  1
12  1   2013-02-12  1

想要的输出:

q_hotel q_date  days_available
1   2013-02-01  3
1   2013-02-02  2
1   2013-02-03  1
1   2013-02-04  0
1   2013-02-05  4
1   2013-02-06  3
1   2013-02-07  2
1   2013-02-08  1
1   2013-02-09  0
1   2013-02-10  0
1   2013-02-11  2
1   2013-02-12  1

现在,如果在需要的日期存在后报价为零,我可以获得天数 - 我找到最接近的不可用日期并计算日期差异。
http://sqlfiddle.com/#!12/1a64c/14

    select q_hotel
  ,q_date
  ,(select extract(day from (min(B.q_date)-A.q_date)) from Table1 B where B.q_date>A.q_date
   and B.q_value=0 and A.q_value<>0)
from Table1 A

但是,当我没有零截止日期时,就会出现问题。

4

1 回答 1

1

这是一个解决方案:

select
    a.q_date
,   a.q_hotel
,   case
        when
            a.q_value = 0
        then
            0
        else
        (
            select
                extract
                ( day from
                    min ( b.q_date ) - a.q_date + interval '1 day'
                )
            from    table1 b
            where   b.q_date >= a.q_date
            and     b.q_hotel = a.q_hotel
            and not exists
            (
                select  1
                from    table1 c
                where   c.q_date = b.q_date + interval '1 day'
                and     b.q_hotel = a.q_hotel
                and     q_value <> 0
            )
        )
    end as days_available
from    table1 a
于 2013-03-06T01:53:57.240 回答