Link to home
Start Free TrialLog in
Avatar of joethermal
joethermal

asked on

SQL multiple joins

Hi, Hope someone can help (using SQL server 2005)...

I have 2 queries that both work perfectly, but I would like to incorporate the second query in to the first so it returns 1 row..
what I want...
Product                       sales_value         sales_quantity       current stock       work_qty
BUN MBFWHITE        498                      6                                40                             30

note that each table has multiple rows and I only want to return 1 row ie
stockm has up to 6 rows because there are different locations
opsahistm has many rows for each sale
bmwohm has many rows for each date
bmwodm has many rows for each date

Link between the 2 queries is product_code in the first and component_code in the second (BUN MBFWHITE)

First Query...
SELECT
      s.product
    , h.sales_value
	, h.sales_quantity
    , SUM(s.physical_qty) AS current_stock
FROM sysdaa.scheme.stockm s
LEFT JOIN (
      SELECT
             product
           , SUM(val) AS sales_value
		   , SUM(quantity) AS sales_quantity
      FROM sysdaa.scheme.opsahistm
      WHERE dated >= '2017-04-01' AND dated < '2017-05-27'
      GROUP BY
            product
      ) h ON s.product = h.product
WHERE s.physical_qty > 0.1 AND s.product = 'BUN MBFWHITE'
GROUP BY
      s.product
    , h.sales_value
	, h.sales_quantity
ORDER BY current_stock DESC;

Open in new window

first query returns...
Product                       sales_value       sales_quantity       current stock
BUN MBFWHITE        498.2                  6                              40


Second query...
SELECT 
sum(d.quantity_required) as work_qty
FROM sysdaa.scheme.bmwodm d
inner join sysdaa.scheme.bmwohm h
on h.works_order = d.works_order
where (h.status = 'C' OR h.status = 'I') 
AND h.completion_date >= '2017-04-01' 
AND h.completion_date < '2017-05-27'
AND d.component_code = 'BUN MBFWHITE' 
AND d.component_unit!='HR';

Open in new window

second query returns...
work_qty
30
ASKER CERTIFIED SOLUTION
Avatar of HainKurt
HainKurt
Flag of Canada 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 joethermal
joethermal

ASKER

Perfect, Thankyou