I want to create three temp tables and then combine their contents like so:
CREATE TABLE #TEMP1
MEMBERITEMCODE VARCHAR(25),
WEEK1USAGE VARCHAR(25),
WEEK1PRICE VARCHAR(25);
INSERT INTO #TEMP1 (MEMBERITEMCODE, WEEK1USAGE, WEEK1PRICE)
SELECT MEMBERITEMCODE, SUM(QTYSHIPPED), PRICE
FROM INVOICEDETAIL
WHERE UNIT=@UNIT AND INVOICEDATE BETWEEN @BEGDATE AND @WEEK1END
GROUP BY MEMBERITEMCODE, PRICE
CREATE TABLE #TEMP2
MEMBERITEMCODE VARCHAR(25),
WEEK2USAGE VARCHAR(25),
WEEK2PRICE VARCHAR(25);
INSERT INTO #TEMP2 (MEMBERITEMCODE, WEEK2USAGE, WEEK2PRICE)
SELECT MEMBERITEMCODE, SUM(QTYSHIPPED), PRICE
FROM INVOICEDETAIL
WHERE UNIT=@UNIT AND INVOICEDATE BETWEEN @WEEK2BEGIN AND @ENDDATE
GROUP BY MEMBERITEMCODE, PRICE
CREATE TABLE #TEMP3
MEMBERITEMCODE VARCHAR(25),
DESCRIPTION VARCHAR(200),
THIS VARCHAR(25),
THAT VARCHAR(25),
THEOTHERTHING VARCHAR(25);
INSERT INTO #TEMP3 (MEMBERITEMCODE, DESCRIPTION, THIS, THAT, THEOTHERTHING)
SELECT MEMBERITEMCODE, DESCRIPTION, THIS, THAT, THEOTHERTHING
FROM INVOICEDETAIL
WHERE UNIT=@UNIT AND INVOICEDATE BETWEEN @BEGDATE AND @ENDDATE
CREATE TABLE #TEMPCOMBINED
MEMBERITEMCODE VARCHAR(25),
DESCRIPTION VARCHAR(200),
THIS VARCHAR(25),
THAT VARCHAR(25),
THEOTHERTHING VARCHAR(25),
WEEK1USAGE VARCHAR(25),
WEEK1PRICE VARCHAR(25);
WEEK2USAGE VARCHAR(25),
WEEK2PRICE VARCHAR(25),
USAGEVARIANCE VARCHAR(25),
PRICEVARIANCE VARCHAR(25),
PRICEVARIANCEPERCENTAGE VARCHAR(25);
INSERT INTO #TEMPCOMBINED (MEMBERITEMCODE, DESCRIPTION, THIS, THAT, THEOTHERTHING, WEEK1USAGE, WEEK1PRICE, WEEK2USAGE, WEEK2PRICE, USAGEVARIANCE,
PRICEVARIANCE, PRICEVARIANCEPERCENTAGE)
SELECT T1.MEMBERITEMCODE, T3.DESCRIPTION, T3.THIS, T3.THAT, T3.THEOTHERTHING, T1.WEEK1USAGE, T1.WEEK1PRICE, T2.WEEK2USAGE, T2.WEEK2PRICE, NULL, NULL, NULL
FROM #TEMP1 T1
LEFT JOIN #TEMP2 T2 ON T1.MEMBERITEMCODE = T2.MEMBERITEMCODE
LEFT JOIN #TEMP3 T3 ON T1.MEMBERITEMCODE = T3.MEMBERITEMCODE
Now I want to replace the placeholder Nulls in the calculated fields, but don't know how to do that. My best idea so far is:
UPDATE #TEMPCOMBINED
SET USAGEVARIANCE = WEEK2USAGE - WEEK1USAGE,
PRICEVARIANCE = WEEK2PRICE - WEEK1PRICE,
PRICEVARIANCEPERCENTAGE = (WEEK2PRICE - WEEK1PRICE) / WEEK1PRICE
Is there a better way (one that actually works, for instance)?