I believe there is a way to do this, but I'm not familiar with ORACLE 10g as many other people are. Here's the scenario:
I'm currently converting Classic ASP pages to ASP.net 2.0. I have a query that is creating a report. It's reporting Sales vs. Previous Sales. What is happening currently is one query is going out to the database and grabbing a complete list of locations that sell our products. Then, it loops through every single row of the locations, and runs some summing operations in SQL.
It goes out to a few other tables, sums up sales quantities, then adds the sum to a table row, etc. Since the locations query returns a lot of results, the query takes a good 2-3 minutes.
My question is how can I consolidate these all into one query.
LOCATIONS QUERY:
SELECT DISTINCT t.location,
l.city,
f.year,
f.customer FROM loc t,
location l, father_table f
WHERE f.number = t.number(+)
AND f.code = '0001'
AND f.c_code = '01'
AND t.location= l.code(+)
AND t.code IN ('C', 'S')
AND t.co_code IN ('G', 'V', 'A', 'D')
AND t.year = '2008'
ORDER BY l.city, f.year
The sum query for each of the rows in the above query is this:
SELECT SUM(nvl(t.sale_quantity,0)) sale_quantity
FROM loc t, father_table f
WHERE f.number = t.number(+)
AND f.code = '0001'
AND f.c_code = '01'
AND f.year = '2008'
AND t.code = 'C'
AND t.location = '1566' <----- EACH ROW'S t.location VALUE
AND t.co_code IN ('G', 'V', 'A', 'D')
GROUP BY t.location, t.code, f.year
Instead of looping through each record of the original query, is there a way I can combine the queries and have the SUM in the Location's query. The key here is that the second query only gets the sales SUM when the t.code = 'C' not 'C' & 'S'