Oracle Aggregation Problem in join between tables [message #603763] |
Thu, 19 December 2013 03:56 |
|
rajamohankumar
Messages: 26 Registered: July 2011 Location: TAMIL NADU
|
Junior Member |
|
|
Dear Friends and Experts,
I have a problem of aggregating and getting correct data from two tables in oracle.I have two tables one is PRODUCT(master table) and another one is PRODUCT_DETAILS(detail table).The table structure of both tables and data has been shown like below,
TABLE 1 :PRODUCT
PRODUCT_ID, PRODUCT, PRICE
100, LAPTOP, 50000
200, MONITOR, 10000
TABLE 2 :PRODUCT_DETAILS
PRODUCT_ID, PRODUCT_NAME, PLACE_OF_PURCHASE
100, SONY, CHENNAI
100, HP, BANGALORE
200, SAMSUNG, CHENNAI
200, DELL , CHENNAI
Now I am trying to write a query to get the sum of price grouping by PRODUCT_ID of master table PRODUCT.The query I used below is,
SELECT
A.PRODUCT_ID,
SUM(A.PRICE)
FROM
HR.PRODUCT A,
HR.PRODUCT_DETAILS B
WHERE B.PRODUCT_ID=A.PRODUCT_ID
GROUP BY A.PRODUCT_ID;
And my result is,
PRODUCT_ID SUM(PRICE)
100 100000
200 20000
The above result is wrong because the Cartesian join and calculation occurs when I joined both the tables and sum the PRICE column.The query aggregate each and every row of detail table and give the result.
But the correct result is,
PRODUCT_ID SUM(PRICE)
100 50000
200 10000
How to solve this problem.
Please help me how to modify my query and get the result correctly.
Thanks.
|
|
|
|
|
|
|
|
|
Re: Oracle Aggregation Problem in join between tables [message #603777 is a reply to message #603768] |
Thu, 19 December 2013 05:34 |
flyboy
Messages: 1903 Registered: November 2006
|
Senior Member |
|
|
You may still make the aggregation in the subquery, something like this (WITH clause is available from 9iR2, otherwise just put that subquery to the WHERE clause directly or make it a view):
WITH product_aggr AS ( SELECT A.PRODUCT_ID, SUM(A.PRICE) PRICE
FROM HR.PRODUCT A
GROUP BY A.PRODUCT_ID )
SELECT A.PRODUCT_ID, A.PRICE
FROM PRODUCT_AGGR A, HR.PRODUCT_DETAILS B
WHERE B.PRODUCT_ID=A.PRODUCT_ID
GROUP BY A.PRODUCT_ID, A.PRICE;
or, if PRODUCT.PRODUCT_ID is unique - and it should, otherwise there would be a real cartesian join for duplicates in PRODUCT - just get rid of SUM around PRICE and add it to the GROUP BY clause.
|
|
|
|
|
|