I'm doing joins incorrectly, and haven't figured out the proper way to get the data I need given the 3 tables below (Customer, SalesHeader, SalesDetail) I'm trying to get line items with 1 Customer per line and the sum of all Sales Details that are in GL Acct 4000 and all Sales Deails in GL Acct 5000. There are many more columns, and several other GL Accounts I want to add, but I've broken it down to the simplest form to try to get it to work. I've provide mock data below and the lastest version of the SQL Statement I had unsuccessfully worked on. It would be greatly appreciated if someone could help me figure out what I'm doing wrong in this SQL Select Statement.
Customer
CustID | CustCode
------------------
1 | AAA111
2 | AN8348
SalesHeader
SH_ID | SH_CustID | SH_GLACCT
-------------------------------
1 | 1 | 4000
2 | 1 | 5000
3 | 1 | 4000
4 | 2 | 5000
SalesDetail
SD_ID | SD_HID | Price
--------------------------
1 | 1 | 100.00
2 | 1 | 540.00
3 | 2 | 100.00
4 | 3 | 600.00
5 | 4 | 50.00
6 | 4 | 75.00
Desired OUTPUT
Carpet = 4000 Pad = 5000
CustID | CustCode | Carpet (Sum all SH_GLACCT = 4000) | PAD (Sum all SH_GLACCT = 5000)
-------------------------------------------------------------------------------------------
1 | AAA111 | 1240.00 | 100.00
2 | AN8348 | 0.00 | 125.00
Incorrect SQL (Both Amounts are over what they should be)
SELECT C.CustID, C.CustCode, SUM(ADH.Price) AS Carpet, SUM(APD.Price) As Pad
FROM Customer AS C
LEFT OUTER JOIN SalesHeader AS ACH On C.CustID = ACH.SH_CustID AND ACH.SH_GLACCT = '4000'
LEFT OUTER JOIN SalesDetail AS ADH On ACH.SH_ID = ADH.SD_HID
LEFT OUTER JOIN SalesHeader AS APH On C.CustID = APH.SH_CustID AND APH.SH_GLACCT = '5000'
LEFT OUTER JOIN SalesDetail AS APD On APH.SH_ID = APD.SD_HID
GROUP BY C.CustID, C.CustCode