Question

I would like to aggregate data at level A and also show detail for one level down, say B. Here is my query that aggregates the amounts at a product_line level (A).

SELECT
  pl.business_unit AS "BU"
 ,p.prod_line
 ,SUM(i.inv_amt) AS "Amount"
FROM   invoice i
LEFT   JOIN product p ON p.item_num = i.item_num
LEFT   JOIN product_level pl ON pl.pl_num = p.pl_num
WHERE  i.date BETWEEN '01-APR-2014' AND '30-APR-2014'
GROUP  BY pl.business_unit
         ,p.prod_line
HAVING SUM(i.inv_amt) > 500000

In the invoice table I have a item_desc field (level B). All item descriptions roll up to a product line description but if I add item_desc to the main query it won't aggregate correctly. I have tried all types of subqueries in FROM and SELECT with no correct result. I haven't used sub queries before but think that is what I need. If so, how would I accomplish having aggregation at the prod_line level while including the item_desc for each line? Thanks for any help!

Was it helpful?

Solution

If the product line is a one to one mapping to item_desc, then you can add in a MAX(item_desc) to your query

SELECT
 pl.business_unit AS "BU"
 ,p.prod_line
 ,max(p.item_desc)
 ,SUM(i.inv_amt) AS "Amount"
FROM   invoice i
LEFT   JOIN product p ON p.item_num = i.item_num
LEFT   JOIN product_level pl ON pl.pl_num = p.pl_num
WHERE  i.date BETWEEN '01-APR-2014' AND '30-APR-2014'
GROUP  BY pl.business_unit
         ,p.prod_line
HAVING SUM(i.inv_amt) > 500000
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top