Advertisement
Guest User

Untitled

a guest
Apr 27th, 2018
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
T-SQL 1.54 KB | None | 0 0
  1. create table #urgent(
  2.      [name]     nvarchar(256)
  3.     ,[rowid]    int
  4.     ,[type]     nvarchar(256)    
  5.     ,[company]  nvarchar(256)  
  6.     ,[date]     datetime  
  7.     ,[kpi]      decimal(19, 2)
  8. );
  9.  
  10. insert into #urgent values
  11.  ('Activity Plan   ', 1, 'Low ', 'MS', '1/01/2018', 10  )
  12. ,('Activity Plan   ', 1, 'Low ', 'MS', '1/02/2018', 20  )
  13. ,('Activity Plan   ', 1, 'Low ', 'MS', '1/03/2018', 30  )
  14. ,('Activity Plan   ', 1, 'Low ', 'MS', '1/04/2018', NULL)
  15. ,('Activity Plan   ', 1, 'Low ', 'MS', '1/05/2018', NULL)
  16. ,('Activity Plan   ', 1, 'Low ', 'MS', '1/06/2018', NULL)
  17. ,('Activity Plan   ', 1, 'Low ', 'MS', '1/07/2018', NULL)
  18. ,('Appointment     ', 2, 'High', 'MS', '1/01/2018', 12  )
  19. ,('Appointment     ', 2, 'High', 'MS', '1/02/2018', 35  )
  20. ,('Appointment     ', 2, 'High', 'MS', '1/03/2018', 44  )
  21. ,('Appointment     ', 2, 'High', 'MS', '1/04/2018', NULL)
  22. ,('Appointment     ', 2, 'High', 'MS', '1/05/2018', NULL)
  23. ,('Appointment     ', 2, 'High', 'MS', '1/06/2018', NULL)
  24. ,('Appointment     ', 2, 'High', 'MS', '1/07/2018', NULL)
  25.  
  26.  
  27. select
  28.      [name]     =   [name]     
  29.     ,[rowid]    =   [rowid]
  30.     ,[type]     =   [type]         
  31.     ,[company]  =   [company]    
  32.     ,[date]     =   [date]     
  33.     ,[kpi]      =   [kpi]  
  34.     ,[value]    =   iif([rowid] = 1, isnull([kpi], [lvalue].[value]), isnull([kpi], [avgvalue].[value]))    
  35. from
  36.     #urgent as  [u]
  37. outer apply
  38.     (
  39.         select top 1 [value] = [kpi] from #urgent where [rowid] = 1 and [kpi] is not null order by [date] desc
  40.     ) as [lvalue]
  41. outer apply
  42.     (
  43.         select [value] = avg([kpi]) from #urgent where [rowid] = 2  and [kpi] is not null
  44.     ) as [avgvalue];
  45.  
  46. drop table #urgent;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement