sql server - how to show year in SQL -
i able group item counts 3 years prior , 3 years after on date, not able break item counts in 3 separate years. take please?
select item, case when date >='12/6/02' , date <'12/6/05' , item ='rice' 'rice prior' case when date >='12/06/05' , date <'12/6/08' , item ='rice' 'rice post' end type, count (qty) rice #temp date >='12/6/02' , date <'12/6/08' group item, case when date >='12/6/02' , date <'12/6/05' , item ='rice' 'rice prior' case when date >='12/06/05' , date <'12/6/08' , item ='rice' 'rice post' end
could please take , break down 3 years please?
running script, result shows
type, rice rice prior 444 rice post 555
my desire output like:
year3, year2, year1 year1, year2, year3 4 44 400 5 500 50
thanks, joe
this should match desired query using pivot , date parameter don't have hard code dates , conditions.
declare @date date = '12/6/2005' select item, [-3] year3, [-2] year2, [-1] year1, [1] year1, [2] year2, [3] year3 ( select item, datediff(dd, @date, [date]) / 365 + case when @date < [date] 1 else -1 end [yr], qty #temp ) t pivot (max(qty) [yr] in ([-3], [-2], [-1], [1], [2], [3])) pvt
the above approach not account leap years. can apply @jpw's approach of using dateadd
aware of leap years. you'll need aware of border scenarios of first , last day of each region. in approach, first match wins, today's date in year "-1".
declare @d date = '12/6/2005' select item, [-3] year3, [-2] year2, [-1] year1, [1] year1, [2] year2, [3] year3 ( select item, case when date between dateadd(year, -3, @d) , dateadd(year, -2, @d) -3 when date between dateadd(year, -2, @d) , dateadd(year, -1, @d) -2 when date between dateadd(year, -1, @d) , dateadd(year, -0, @d) -1 when date between dateadd(year, +0, @d) , dateadd(year, +1, @d) 1 when date between dateadd(year, +1, @d) , dateadd(year, +2, @d) 2 when date between dateadd(year, +2, @d) , dateadd(year, +3, @d) 3 else null end [yr], qty #temp ) t pivot (max(qty) [yr] in ([-3], [-2], [-1], [1], [2], [3])) pvt
Comments
Post a Comment