Sql 求有条件的非破缺周期
一张桌子上有每天的旅馆配额。如何获得酒店每天可用的天数Sql 求有条件的非破缺周期,sql,postgresql,postgresql-9.2,Sql,Postgresql,Postgresql 9.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-0
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
现在我可以得到的天数,如果有零报价后,需要的日期存在-我找到最近的不可用日期,并计算日期差。
但当我没有零截止日期时会出现问题。这里有一个解决方案:
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
q_值是多少?不是一个超级信息列名称。。。。空缺数目?至于这个问题,听起来你想找出覆盖范围内的每一天,至少有一个空缺的连续天数。正确吗?另外,是否保证输入表中的条目是连续的?i、 e.2013-02-01之后是否会出现2013-02-03,跳过2013-02-02的条目?如果是这样的话,02年是否应假设零假期?连续-不保证,缺失日期意味着零假期。q_值-是,空缺数量。
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