I am trying to create a query that will list each item and then the number of times this item was sold with two yearly count columns. The first column needs to be the year 2011 and the second column needs to be 2012. How do I restructure this query to give the correct yearly totals. This script is close but for each line it repeats the same data 3 times.
select y1.itemnmbr,y1.ITEMDESC,y1.NumberPerYear as '2011',y2.NumberPerYear as '2012'
from SOP30300 sl
inner join SOP30200 sh on sl.SOPNUMBE=sh.SOPNUMBE and sl.SOPTYPE=sh.SOPTYPE
inner join
(
select itemnmbr,itemdesc,COUNT(itemnmbr) as NumberPerYear
from SOP30300 sl
inner join SOP30200 sh on sl.SOPNUMBE=sh.SOPNUMBE and sl.SOPTYPE=sh.SOPTYPE
where custnmbr='195' and sh.SOPTYPE=3 and YEAR(sh.docdate)=2011
group by ITEMNMBR,ITEMDESC
) y1 on sl.itemnmbr= y1.itemnmbr
inner join
(
select itemnmbr,COUNT(itemnmbr) as NumberPerYear
from SOP30300 sl
inner join SOP30200 sh on sl.SOPNUMBE=sh.SOPNUMBE and sl.SOPTYPE=sh.SOPTYPE
where custnmbr='195' and sh.SOPTYPE=3 and YEAR(sh.docdate)=2012
group by ITEMNMBR,ITEMDESC
) y2 on sl.itemnmbr= y2.itemnmbr
where custnmbr='195' and sh.SOPTYPE=3
Microsoft SQL Server 2008Microsoft SQL Server 2005