Link to home
Start Free TrialLog in
Avatar of mainrotor
mainrotor

asked on

I need help combining two queries in SQL Server 2008

Hi experts,
I need your assistance combining the two queries below.
I need to take the sum of query #1 and subtract the sum of query #2 from it.
How can I do this?  I have listed both my queries below.

NOTE: The PONUMBER field in query 1 matches the PONUMBER field in query #2.


--Query 1
SELECT 
  SUM(I.[QTYORDER])
  FROM POPHEADER as I
  inner join POPDETAIL as P
  on I.PONUMBER = P.PONUMBER
  where I.[POLNESTA] not in (4,5,6) and P.[DOCDATE] >= '1/1/2014' and I.[ITEMNMBR] = '209822011'
  and I.POTYPE =1
  
--Query 2
SELECT SUM(QTYRECVD) AS QTY
     FROM INVOICE_TABLE
where [DATERECD] >= '1/1/2014' and RCPTSOLD = 0
and  [PONUMBER] = '07277' and [ITEMNMBR] =  '209822011'

Open in new window



Thanks in advance,
mrotor
Avatar of Anthony Perkins
Anthony Perkins
Flag of United States of America image

Well, your second query only contains PONUMBER = '07277', so you just could do this:
SELECT  SUM(I.[QTYORDER])
FROM    POPHEADER AS I
        INNER JOIN POPDETAIL AS P ON I.PONUMBER = P.PONUMBER
WHERE   I.[POLNESTA] NOT IN (4, 5, 6)
        AND P.[DOCDATE] >= '1/1/2014'
        AND I.[ITEMNMBR] = '209822011'
        AND I.POTYPE = 1
	AND i.PONUMBER <> '07277'

Open in new window

But I get the feeling you are looking for something more than that, so perhaps this:
--Query 1
SELECT  SUM(I.[QTYORDER])
FROM    POPHEADER AS I
        INNER JOIN POPDETAIL AS P ON I.PONUMBER = P.PONUMBER
        LEFT JOIN (SELECT   PONUMBER
                   FROM     INVOICE_TABLE
                   WHERE    [DATERECD] >= '1/1/2014'
                            AND RCPTSOLD = 0
                            --AND [PONUMBER] = '07277'
                            AND [ITEMNMBR] = '209822011'
                   GROUP BY PONUMBER
                  ) d ON i.PONUMBER = d.PONUMBER
WHERE   I.[POLNESTA] NOT IN (4, 5, 6)
        AND P.[DOCDATE] >= '1/1/2014'
        AND I.[ITEMNMBR] = '209822011'
        AND I.POTYPE = 1
        AND d.PONUMBER IS NULL

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of PortletPaul
PortletPaul
Flag of Australia 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
Ah, never mind, it looks like I misread the question.