I have query like the following
SELECT a.*, b.*
(SELECT ATTR1, ATTR2, sum(QUANTITY) AS TOTAL_QTY,
ATTR3 FROM TABLE_A
WHERE ATTR4 > 0
GROUP BY ATTR1, ATTR2, ATTR3) a,
TABLE_B b
WHERE a.ATTR1 = b.ATTR1
AND a.ATTR2 = b.ATTR2
I need to GROUP BY only ATTR1 to calculate the correct TOTAL_QTY, but the only reason I am grouping other attributes because Oracle requires that if GROUP BY clause is present then all SELECT attributes should be in the GROUP BY clause too.
This means every time I need an attribute in this query from Table_A then I need to put it in GROUP BY too. That not only looks ugly, but can have performance impact and maybe unforseen side-effect.
How do I rewrite the above query to calculate the TOTAL_QTY in each ATTR1 groups, without the GROUP BY clause?
Use Oracle analytic functions. Change the inline view for
table_ato something like:This may need tweaking a bit, but that’s the basic idea.