Guest User

Untitled

a guest
Jan 22nd, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. SELECT
  2. 1 AS id,
  3. {ts '2012-09-24 10:00:00'} AS start,
  4. {ts '2012-09-24 11:00:00'} AS stop,
  5. 10 AS priority
  6. INTO #TABLE
  7. UNION ALL SELECT 2, {ts '2012-09-24 10:15:00'}, {ts '2012-09-24 12:00:00'}, 5
  8. UNION ALL SELECT 3, {ts '2012-09-24 10:30:00'}, {ts '2012-09-24 12:30:00'}, 1
  9. UNION ALL SELECT 4, {ts '2012-09-24 11:30:00'}, {ts '2012-09-24 13:00:00'}, 15
  10.  
  11. SELECT * FROM #TABLE;
  12. DROP TABLE #TABLE;
  13.  
  14. Start Stop Priority
  15. 2012-09-24 10:00 2012-09-24 11:00 10
  16. 2012-09-24 11:00 2012-09-24 11:30 5
  17. 2012-09-24 11:30 2012-09-24 13:00 15
  18.  
  19. ;with cte as
  20. (select start as timepoint from @table union select stop from @table)
  21. ,cte2 as (select *, ROW_NUMBER() over (order by timepoint) rn from cte)
  22.  
  23. select id, MIN(ts) as starttime, max(te) as stoptime, maxpri
  24. from @table t2
  25. inner join
  26. (
  27. select ts, te, MAX(priority) as maxpri
  28. from @table t1
  29. inner join
  30. (
  31. select c1.rn, c1.timepoint as ts, c2.timepoint as te
  32. from cte2 c1
  33. inner join cte2 c2 on c1.rn+1 = c2.rn
  34. ) v
  35. on t1.start<v.te and t1.stop>v.ts
  36. group by ts, te
  37. ) v
  38. on t2.priority = v.maxpri
  39. and ts>=start and te<=stop
  40. group by id, maxpri
  41. order by starttime
Add Comment
Please, Sign In to add comment