简体   繁体   English

如何在最小和最大日期创建GROUP BY

[英]How to create GROUP BY on min and max date

I have a database table like this 我有这样的数据库表

emp_id start-date  end_date    title    location
111    1-JAN-2000  31-DEC-2003 MANAGER  NYO
111    1-JAN-2003  31-DEC-2005 MANAGER  BOM
111    1-JAN-2006  31-DEC-2007 CFO      NYO
111    1-JAN-2008  31-DEC-2015 MANAGER  NYO

I have created a SQL code already with GROUP BY and min , max function 我已经使用GROUP BY和min,max函数创建了一个SQL代码

select emp_id,min(start_date),max(end_date),title
from table1
group by emp_id,title

What is expect is this: 期望的是:

111 1-JAN-2000 31-DEC-2005 MANAGER
111 1-JAN-2006 31-DEC-2007 CFO
111 1-JAN-2008 31-DEC-2015 MANAGER

What i am getting is: 我得到的是:

111 1-JAN-2000 31-DEC-2015 MANAGER 
111 1-JAN-2006 31-DEC-2007 CFO

This is a type of gaps-and-islands problem with date-chains. 这是日期链的一种“空白与孤岛”问题。 I would suggest using a left join to find where the islands start. 我建议使用left join来查找岛屿的起点。 Then a cumulative sum and aggregation: 然后是一个累加的总和:

select emp_id, title, min(start_date), max(end_date)
from (select t.*,
             sum(case when tprev.emp_id is null then 1 else 0 end) over
                 (partition by t.emp_id, t.title order by t.start_date) as grouping
      from t left join
           t tprev
           on t.emp_id = tprev.emp_id and
              t.title = tprev.title and
              t.start_date = tprev.end_date + 1
     ) t
group by grouping, emp_id, title;

try like below by using window function find the gap and make it the group 如下尝试使用窗口功能找到差距,并使其成为组

with cte1 as
(
select a.*,
row_number()over(partition by emp_id,title order by start-date) rn,
row_number() over(order by start-date) rn1
from table_name a
) select emp_id,
  min(start-date),
  max(end_date),
  max(title)
  from cte1 group by emp_id, rn1-rn

demo link 演示链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM