Advertisement
Guest User

Untitled

a guest
Jun 19th, 2019
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. declare @t table (employeeid int, datecol date, status varchar(2) )
  2.  
  3. insert into @t values (10001, '01-05-2016', 'P'),
  4. (10001, '02-05-2016', 'P'),
  5. (10001, '03-05-2016', 'P'),
  6. (10001, '04-05-2016', 'P'),
  7. (10001, '05-05-2016', 'A'),
  8. (10001, '06-05-2016', 'P'),
  9. (10001, '07-05-2016', 'P'),
  10. (10001, '08-05-2016', 'L'),
  11. (10002, '07-05-2016', 'P'),
  12. (10002, '08-05-2016', 'L')
  13.  
  14. --select * from @t
  15.  
  16. select * ,
  17. SUM(case when status = 'P' then 1 else 0 end) OVER (PARTITION BY employeeid ORDER BY employeeid, datecol
  18. ROWS BETWEEN UNBOUNDED PRECEDING
  19. AND current row)
  20. from
  21. @t
  22.  
  23. ;with cte as
  24. (
  25. select employeeid , datecol , ROW_NUMBER() over(partition by employeeid order by employeeid, datecol) rowno
  26. from
  27. @t where status = 'P'
  28. )
  29. select t.*, cte.rowno ,
  30. case when ( isnull(cte.rowno, 0) = 0)
  31. then LAG(cte.rowno) OVER (ORDER BY t.employeeid, t.datecol)
  32. else cte.rowno
  33. end LagValue
  34. from @t t left join cte on t.employeeid = cte.employeeid and t.datecol = cte.datecol
  35. order by t.employeeid, t.datecol
  36.  
  37. SELECT
  38. main.EmployeeID,
  39. main.[Date],
  40. main.[Status],
  41. (
  42. SELECT SUM(CASE WHEN t.[Status] = 'P' THEN 1 ELSE 0 END)
  43. FROM [TableName] t
  44. WHERE t.EmployeeID = main.EmployeeID AND t.[Date] <= main.[Date]
  45. ) as TotalPresent
  46. FROM [TableName] main
  47. ORDER BY
  48. main.EmployeeID,
  49. main.[Date]
  50.  
  51. select *
  52. , (select count(retail) from p g
  53. where g.date <= p.date and g.id = p.id and retail = 'P')
  54. from p
  55. order by ID, Date;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement