Avatar of rwheeler23
rwheeler23
Flag 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
Microsoft SQL Server 2008Microsoft SQL Server 2005

Avatar of undefined
Last Comment
rwheeler23

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
jogos

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
rwheeler23

ASKER
Excellent solution and advice. Thank you.
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes