Advertisement
Guest User

Untitled

a guest
Jun 25th, 2018
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. with dates as (
  2.     select date_trunc('month', now() + (interval '1' month * generate_series(0,11))) as date
  3. ),
  4. all_vc as (
  5.     select distinct cv.description as description, cv.id as id
  6.     from static_referent.callvertical as cv
  7.     join historian.callhistorian as ch on ch.call_vertical = cv.id
  8.     join dynamic_referent.callbacktodo as cdt on cdt."call" = ch.id
  9. ),
  10. date_vc as (
  11.     select dates.date as date, all_vc.description as description, all_vc.id as id
  12.     from dates
  13.     cross join all_vc
  14. )
  15. min_date as (
  16.     select min(date_vc.date) as date, date_vc.id
  17.     from date_vc
  18.     group by date_vc.id
  19. ),
  20. callbacks as (
  21.     select cdt."date" as date, hc.call_vertical as id
  22.     from dynamic_referent.callbacktodo as cdt
  23.     join historian.callhistorian as hc on hc.id = cdt."call"
  24. ),
  25. prev_date as (
  26.     select min_date.date as date, min_date.id as id, count(date_trunc('month', cb.date)) as count
  27.     from min_date
  28.     join callbacks as cb on date_trunc('month', cb.date) < min_date.date and cb.id = min_date.id
  29.     group by min_date.id, min_date.date
  30. ),
  31. c_count as (
  32.     select count(date_trunc('month', cb.date)) as count, date_trunc('month', cb.date) as date, cb.id
  33.     from callbacks as cb
  34.     group by date_trunc('month', cb.date), cb.id
  35. )
  36. select to_char(date_vc.date, 'YY/MM'), date_vc.description as call_vertical, (coalesce(c_count.count, 0) + coalesce(prev_date.count, 0)) as count
  37. from date_vc
  38. left join c_count on c_count.date = date_vc.date and date_vc.id = c_count.id
  39. left join prev_date on prev_date.date = c_count.date and prev_date.id = c_count.id
  40. order by to_char(date_vc.date, 'MM') asc, call_vertical
  41. ;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement