我有日期范围(例如“20170301”和“20170701”)和表格:
id name start end
1 first 2017-01-01 2017-10-01 (yyyymmdd)
2 second 2017-02-01 2017-02-01``
3 third 2017-02-01 2017-06-01
我必须计算是否每天都有一些事件来自范围 并返回这些日期。
例如20170301 - 有两个事件 - > count = 2 - >选择这个 20170401 - 2 ... ... 20170701 - 没有事件 - > count = 0 - >不要选择这个
我的查询仅包含start_date:
select to_char(t.start_date, 'yyyymmdd') as DAY
from table t
where to_char(t.start_date, 'yyyymmdd') between 20170301 and 20170304
group by to_char(t.start_date, 'yyyymmdd')
having count(*) > 0
我应该按照输入范围的每一天进行分组,以确定每天的范围内是否至少有一个事件。 (每天范围增量的某种群体)。
是否有可能实施两种方法?或者您可以推荐不同的方法吗?
答案 0 :(得分:0)
使用递归子查询分解子句:
Oracle安装程序:
CREATE TABLE table_name ( id, name, start_date, end_date ) AS
SELECT 1, 'first', DATE '2017-01-01', DATE '2017-10-01' FROM DUAL UNION ALL
SELECT 2, 'second', DATE '2017-02-01', DATE '2017-02-01' FROM DUAL UNION ALL
SELECT 3, 'third', DATE '2017-02-01', DATE '2017-06-01' FROM DUAL;
<强>查询强>:
WITH calendar ( day ) AS (
SELECT DATE '2017-03-01' FROM DUAL
UNION ALL
SELECT day + 1 FROM calendar WHERE day < DATE '2017-07-01'
)
SELECT day, COUNT(id)
FROM calendar
INNER JOIN
table_name
ON ( day BETWEEN start_date AND end_date )
GROUP BY day
ORDER BY day;