【发布时间】:2015-04-08 15:32:57
【问题描述】:
我正在尝试配对从我的 SQL 获得的日期。目前的输出如下所示:
start_date end_date
2015-02-02 2015-02-02
2015-02-02 2015-02-03
2015-02-03 2015-02-03
2015-04-12 2015-02-12
我希望将输出配对,以便选择日期组的最小和最大日期,以便输出如下所示:
start_date end_date
2015-02-02 2015-02-03
2015-04-12 2015-02-12
使用第一个响应,我得到类似这样的信息,我相信我的格式错误,我得到的日期对与以前相同,但它确实运行了。
select min(date), max(date)
from (select date,
sum(case when sum(inc) = 0 then 1 else 0 end) over (order by date desc) as grp
from (select t1.datev as date, 1 as inc
from table2 t1,
table3 c,
table4 cr
where t1.datev between date(c.e_start_date) and date(c.e_end_date)
and t1.datev not in (select date(temp.datev) from mdmins11.temp temp where temp.number < 4000 and temp.organisation_id = 11111)
and c.tp_cd in (1,6)
and cr.from_id = c.id
and cr.organisation_id = 11111
union all
select t.datev as date, -1 as inc
from table1 t,
table3 c,
table4 cr
where t.datev between date(c.e_start_date) and date(c.e_end_date)
and t.datev not in (select date(temp.datev) from mdmins11.temp temp where temp.number < 4000 and temp.organisation_id = 11111)
and c.tp_cd in (1,6)
and cr.from_id = c.id
and cr.organisation_id = 11111
) t
group by date
) t
group by grp;
【问题讨论】:
-
如果没有对基表和其中数据的描述,以及您希望如何将数据关联到组中,我们几乎无法开始。答案可能是涉及
min()和max()函数的聚合查询,但我只能这么说。