Advertisement
Guest User

Untitled

a guest
Nov 18th, 2019
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. with a as (select contract_id from contracts where contact_id=106 and start_date <= CURRENT_DATE and end_date >= CURRENT_DATE),
  2. b as (select schedule_id from scheduled_contracts where contract_id in (select * from a)),
  3. c as (select schedule_id from schedules s where s.schedule_id in (select * from b)
  4.     and s.start_date <= CURRENT_DATE and s.end_date >= CURRENT_DATE),
  5. d as (select schedule_id, start_date from schedules s where s.schedule_id in (select * from b)
  6. and s.start_date > CURRENT_DATE),
  7. e as (select schedule_id, count(*) as num_sessions from sessions where schedule_id
  8.     in (select * from c) group by schedule_id order by num_sessions desc limit 1),
  9. f as (select s.schedule_id, d.start_date, count(*) as num_sessions from sessions s inner join d on s.schedule_id = d.schedule_id where s.schedule_id
  10.     in (select schedule_id from d) group by s.schedule_id, d.start_date order by d.start_date asc, num_sessions desc limit 1),
  11. g as (select schedule_id as holder,
  12.     case
  13.         when (select count(*) from e) = 0 then
  14.             case
  15.                 when (select count(*) from f) = 0 then null
  16.                 else (select schedule_id from f)
  17.             end
  18.         else (select schedule_id from e)
  19.     end from b),
  20. h as (select distinct schedule_id from g),
  21. i as (select term_program_location_id from term_program_location_schedules tpls where tpls.schedule_id in (select * from h)),
  22. j as (select tpl.term_id, tpl.program_region_id, tpl.team_program_id from term_program_location tpl where tpl.term_program_location_id in (select * from i))
  23. select tpl.program_region_id, tpl.term_id, tp.program_id from j tpl, team_program tp where tp.team_program_id = tpl.team_program_id;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement