SQL Записи группы серверов на основе других столбцов - PullRequest
0 голосов
/ 07 августа 2020

Я работаю над таблицей, содержащей данные о сотрудниках. В таблице есть исторические записи о сотрудниках по отделам и годам следующим образом:

enter image description here

Now I want to consolidate records based on EmployeeId, Department and get the Min FromYear and Max ToYear like this:

enter image description here

I tried to use a query :

Select EmployeeId, Department, MIN(FromYear), MAX(ToYear)
from Employee
GROUP BY EmployeeId, Department

But this query fails for the employee with ID 3 as it returns me only 2 rows: enter image description here

I have added a similar structure and query here: http://sqlfiddle.com/#! 9 / 6f1e53 / 5

Любая помощь будет принята с благодарностью!

Ответы [ 2 ]

4 голосов
/ 07 августа 2020

Это проблема промежутков и островов. Определите острова, используя lag() и совокупную сумму. Затем агрегируйте:

select employeeid, department, min(fromyear), max(toyear)
from (select e.*,
             sum(case when prev_toyear >= fromyear - 1 then 0 else 1 end) over (partition by employeeid order by fromyear) as grp
      from (select e.*,
                   lag(toyear) over (partition by employeeid, department order by fromyear) as prev_toyear
            from employee e
           ) e
      ) e
group by employeeid, department, grp
order by employeeid, min(fromyear);

Здесь - скрипт db <>.

0 голосов
/ 08 августа 2020

вы также можете использовать самостоятельное присоединение

выберите a.employeeid, min (a.fromyear), max (b.toyear) из emp a внутреннее соединение emp b в группе a.employeeid = b.employeeid от a.employeeid

...