I am trying to get the order number, order date, the number of cartons sold, the number of pack sold(which is a multiple of the cartons), and the customer ID and the Customer State.
I have the script working well without the State added. When I add the state, about 10% of my numbers get skewed. I determined that when I look in the address table to get the state, it causes me a problem.
In the address table, it give contact address (4), ship to address (5), and bill to address (6). This should be easy in that I make a condition where the type = 5 for the ship address.
The problem is that we have other software that imports customers. Each time it is run, it creates another instead of updating. So for most customers, I have 3 entries (4,5,6). For some customers, I have 33. That is the largest amount. What it then does is that it takes my numbers for cartons and packs and multplies it by the number of type 5 entries there are for each customer code. If there is one entry of type 5 then the number is correct. If there are 10 then it multiplies my numbers by 10.
How can I make this work so it only gets the state (A.STATE) in the code and does not multiply it?
Thanks for any and all help!
SELECT CASE WHEN I.STATUS = 9
THEN 'Invoice'
ELSE 'Return'
END AS DOCTYPE,
I.ORDER_NO, I.ORDER_DATE,
CASE WHEN I.STATUS = 9
THEN SUM(X.QTY_SHIP)
ELSE SUM(X.QTY_SHIP * -1)
END AS CARTONS,
CASE WHEN I.STATUS = 9
THEN SUM(CASE WHEN (IT.SALE_MEAS = 'CARTON' or IT.SALE_MEAS = '8/25-PK') THEN X.QTY_SHIP * 10 ELSE X.QTY_SHIP * 5 END)
ELSE -1 * SUM(CASE WHEN IT.SALE_MEAS = 'CARTON' THEN X.QTY_SHIP * 10 ELSE X.QTY_SHIP * 5 END)
END AS Packs,
C.CUST_CODE, A.STATE
FROM INVOICES I WITH (NOLOCK)
INNER JOIN X_INVOIC X WITH (NOLOCK) ON I.DOC_NO = X.ORDER_NO AND I.STATUS = X.STATUS
INNER JOIN ITEMS IT WITH (NOLOCK) ON X.ITEM_CODE = IT.ITEMNO
INNER JOIN CUST C ON I.CUST_CODE = C.CUST_CODE
INNER JOIN ADDRESS A ON C.CUST_CODE = A.CUST_CODE
WHERE I.STATUS IN (9,12)
AND A.TYPE = 5
AND IT.CATEGORY IN ('CIGS','CIGSSPL','CIGS25')
AND (I.ORDER_DATE >= '01/01/2008') AND (I.ORDER_DATE < '1/01/2009')
GROUP BY I.ORDER_DATE, I.ORDER_NO, A.STATE, I.STATUS, C.CUST_CODE
ORDER BY I.ORDER_DATE, I.ORDER_NO
Feelfree to email me at bzkjoe59@gmail.com
Have a great day!