想要一个SQL语句来计算数字

时间:2017-05-13 06:54:38

标签: sql oracle11g

我有一个表有3列id,open_time,close_time,数据看起来像这样:

enter image description here

然后我想要一个SQL得到这样的结果:
enter image description here

规则是:如果日期等于开放时间则为新,如果日期> open_time和date< close_time然后打开,如果日期等于close_time则关闭

如何在Oracle中编写SQL?

1 个答案:

答案 0 :(得分:1)

首先在运行中构建一个表,其中包含从表中最小日期到今天的所有日期。你需要一个递归查询。

然后为这三种状态即时建立一个表格。

现在交叉加入两个以获得所有组合。这些是你想要的行。

其余的是每天计算和状态,可以通过连接和分组或使用一个或多个子查询来实现。我正在展示加入:

with days(day) as 
(
  select min(open_time) as day from opentimes
  union all
  select day + 1 from days where day < trunc(sysdate)
)
, statuses as
(
  select 'New' as status, 1 as sortkey from dual
  union all
  select 'Open' as status, 2 as sortkey from dual
  union all
  select 'Close' as status, 3 as sortkey from dual
)
select
  d.day, 
  s.status,
  count(case when (s.status = 'New' and d.day = o.open_time)
               or (s.status = 'Open' and d.day = o.close_time)
               or (s.status = 'Close' and d.day > cls.open_time and d.day < cls.close_time)
             then 1 end) as cnt
from days d
cross join statuses s
join opentimes o on d.day between o.open_time and o.close_time
group by d.day, s.status
order by d.day, max(s.sortkey);