Link to home
Start Free TrialLog in
Avatar of rwheeler23
rwheeler23Flag for United States of America

asked on

SQL Syntax mulitple count columns

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
ASKER CERTIFIED SOLUTION
Avatar of jogos
jogos
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of rwheeler23

ASKER

Excellent solution and advice. Thank you.