I have the need to pull data from three tables. Two tables are going to have aggregate functions. My first query works, but when I join in the second aggregate, then my numbers are incorrect.Here is one version of the query where my On Hand Qty is incorrect (I believe it sums up for every record I have in APFVT, which is incorrect):SELECT PM.PART_ID, PM.STD_UNIT_COST, SUM(SS.ON_HAND_QTY) AS "ON HAND QTY", MAX(VT.VOUCHER_ID) AS "VOUCHER ID"FROM ICFPM PM, ICFSS SS, APFVT VTWHERE PM.PART_TYPE = 'B' AND SS.ON_HAND_QTY > 0 AND (PM.PART_ID = SS.PART_ID) AND (PM.PART_ID = VT.PART_ID)GROUP BY PM.PART_ID, PM.STD_UNIT_COST
The quantity on the first item should be 76, but I get 1444. There is a 1 - many relationship between ICFPM and ICFSS as well as ICFPM and APFVT.Here is another version of the query that I am trying, but in this case I get two records, both with half the information I need. If I could get this to produce 1 record for each Part ID with the corresponding information that would be great.SELECT VT.PART_ID, CONVERT(INT, '') AS "UNIT COST", CONVERT(INT, '') AS "ON HAND QTY", MAX(VT.VOUCHER_ID) AS "VOUCHER ID"FROM APFVT VTWHERE VT.PART_ID <> ''GROUP BY VT.PART_ID UNION SELECT PM.PART_ID, PM.STD_UNIT_COST, SUM(SS.ON_HAND_QTY) AS "ON HAND QTY", ''FROM ICFPM PM LEFT OUTER JOIN ICFSS SS ON PM.PART_ID = SS.PART_IDWHERE PM.PART_TYPE = 'B' AND SS.ON_HAND_QTY > 0 AND (PM.PART_ID = SS.PART_ID)GROUP BY PM.PART_ID, PM.STD_UNIT_COST
Here is what I get:PART_ID UNIT COST ON HAND QTY VOUCHER ID180-001202 0.000000 0.0000 0011030144104180-001202 133.710000 76.0000
Here is what I would like to get.PART_ID UNIT COST ON HAND QTY VOUCHER ID180-001202 133.710000 76.0000 0011030144104
Any help would be greatly appreciated. I have tried dozens of variations and can not hit the exact statement I need.