Pregunta

INSERT INTO RESULTS(Month,Region,Item,
Yield12mo,UnitsShipped)

select m.Period,s.Region,s.Item,avg(s.Yield),
sum(s.ShippedQty)

from SALES s, PERIOD m
where s.BuyDate >= date_sub(m.StartDate,INTERVAL 12 MONTH)
and s.BuyDate <= m.EndDate
group by s.Item;

Sales table contains items, sale dates, prices, etc.

Period table contains the time frame in question (altered by an auto-script)

I need to find a way to add Yield12Mo to RESULTS only if the total qty shipped for each item between the selected date range is >= to 10 and that the Region + Item combo is not already in the results table.

If less than 10 shipped in that time period or if the Region + Item combo is already in results, then do not add.

I know I need some type of IF statement or CASE statement combined with a join, but I'm new to this and cannot figure it.

Any help is greatly appreciated. Thank you!

¿Fue útil?

Solución

This is a tough one because I know so little about your schema, but I think the following should work. DISCLAIMER: I have only ever worked in MSSQL, not MYSQL, so some of the syntax may be slightly different...

INSERT INTO RESULTS(Month, Region, Item, Yield12mo, UnitsShipped)

select m.Period,s.Region,s.Item,avg(s.Yield), sum(s.ShippedQty)

from SALES s INNER JOIN PERIOD m -- my preferred method, but yours may work fine
ON s.BuyDate >= date_sub(m.StartDate,INTERVAL 12 MONTH)
    and s.BuyDate <= m.EndDate
where
--First we'll try and filter out anything that already exists in RESULTS
  s.Sales NOT IN
  (
   select Sales.Sales 
   from Sales
        inner join Results 
          ON  sales.Region = Results.Region
          AND sales.Item = Results.Item
  )
group by s.Item
--We still have to make it so that we only get ones that have a ShippedQty >=10.
HAVING sum(s.ShippedQty) >= 10
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top