I have a sales table that is keyed by sku, store, and period. From this, I need a query that returns a record containing both This Year and Last Year's information.
The logic behind the query below is this:
- Calculate last year sales (in the with table)
- Calculate this year sales in the main body (WHERE CLAUSE)
- Join the "LAST YEAR" table to the main table. Only joining on sku and store (you cannot join by date because they will not overlap)
My problem is that the results for last year are not the entire amount. My results act as though I am doing a LEFT JOIN, and not returning all the results from the "LAST YEAR" table.
Additional Detail:
- When I run a LEFT JOIN, and a FULL OUTER JOIN, I get the same results.
- When I execute the "WITH" clause independently, the results are correct
- When I run the entire statement, last year sales are not the full amount
The code below has been simplified some... I'm not so worried about the syntax, but more about the LOGIC. If anyone has any ideas, or know possible flaws in my logic, I'm all ears! Thanks in advance!
WITH lastYear AS (
SELECT
spsku "sku",
spstor "store",
sum(spales) "sales_ly"
FROM SALES
WHERE spyypp BETWEEN 201205 AND 201205
GROUP BY spstor, spsku
)
SELECT
Sales_report.spstor "store",
sum(spales) "bom_retail",
sum(LY."sales_ly") "sales_ly"
FROM SALES Sales_report
FULL OUTER JOIN lastYear LY ON LY."sku" = spsku AND LY."store" = spstor
WHERE spyypp BETWEEN 201305 AND 201305
GROUP BY spstor