Advertisement
Guest User

Untitled

a guest
Nov 14th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
T-SQL 1.00 KB | None | 0 0
  1. declare @last6months table (monthId int);
  2. insert @last6months(monthId)
  3. values
  4.     (MONTH(DATEADD(month, -5, GETDATE()))),
  5.     (MONTH(DATEADD(month, -4, GETDATE()))),
  6.     (MONTH(DATEADD(month, -3, GETDATE()))),
  7.     (MONTH(DATEADD(month, -2, GETDATE()))),
  8.     (MONTH(DATEADD(month, -1, GETDATE()))),
  9.     (MONTH(GETDATE()))
  10. ;
  11.  
  12. SELECT
  13.     ISNULL(daysAvg.PickPerStoreMonthly, 0) PickPerStoreMonthly,
  14.     last6months.monthId
  15. FROM
  16.     (select * from @last6months) last6months
  17. LEFT JOIN (
  18.     SELECT
  19.         AVG (DATEDIFF ( day, item.CreateDate , point.Arrived)) PickPerStoreMonthly,
  20.         MONTH(point.Arrived) monthId   
  21.     FROM
  22.         Location location WITH (NOLOCK)
  23.         LEFT JOIN RoutePoint point WITH (NOLOCK) ON point.LocationId = location.Id
  24.         LEFT JOIN Route route WITH (NOLOCK) ON route.Id = point.RouteId
  25.         LEFT JOIN Item item WITH (NOLOCK) ON item.RouteId = route.Id
  26.  
  27.     WHERE
  28.         point.Arrived > DATEADD(month, -5, GETDATE())
  29.         AND location.Id = 18
  30.     GROUP BY (MONTH(point.Arrived))    
  31. ) daysAvg ON daysAvg.monthId = last6months.monthId
  32. ;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement