I have to generate a report which shows sales for each country, per year. (Fixed amount of years)
I managed to create this query:
SELECT sum(dwfactsales.amount) as "2009" INTO v_dwrecord."2009"
FROM dwfactsales
JOIN dwdimcustomer ON dwdimcustomer.customerkey = dwfactsales.customerkey
JOIN dwdimdate ON dwdimdate.datekey = dwfactsales.datekey
WHERE dwdimcustomer.country = 'Australia' and dwdimdate.calenderyear = 2009;
v_dwreport(1) := v_dwrecord;
This query works perfectly to gather the amount of sales for the year 2009 in Australia. However, I want to use this query for each year and each country. I can iterate the countries, but I can't seem to iterate the years.
My record and table is declared as:
TYPE t_DWRECORD IS RECORD(
COUNTRY dwdimcustomer.country%TYPE,
"2009" NUMBER,
"2010" NUMBER,
"2011" NUMBER,
"2012" NUMBER,
"2013" NUMBER,
"2014" NUMBER,
TOTAL NUMBER
);
TYPE t_DWTABLE IS TABLE OF t_DWRECORD INDEX BY BINARY_INTEGER;
I created the following snippet:
v_count := 0;
FOR country_rec IN (SELECT DISTINCT country FROM dwdimcustomer order by country asc) LOOP
FOR year_rec IN (SELECT DISTINCT calenderyear FROM dwdimdate order by calenderyear asc) LOOP
SELECT sum(dwfactsales.amount) as "2009" INTO v_dwrecord."2009"
FROM dwfactsales
JOIN dwdimcustomer ON dwdimcustomer.customerkey = dwfactsales.customerkey
JOIN dwdimdate ON dwdimdate.datekey = dwfactsales.datekey
WHERE dwdimcustomer.country = country_rec.country and dwdimdate.calenderyear = year_rec.calenderyear;
v_dwreport(v_count) := v_dwrecord;
v_count := v_count+1;
END LOOP;
END LOOP;
As you can see there's still the part INTO v_dwrecord."2009"
, I want to change it to the year_rec.calenderyear
in each iteration. How can I do this? I tried using the EXECUTE IMMEDIATE
with a VARCHAR2(500)
variable, which contained a dynamic query. It looked like this: INTO v_dwrecord." || year_rec.calenderyear ||"
.
Working with the EXECUTE IMMEDIATE
gave me the following errors:
00000 - "SQL command not properly ended" *Cause:
*Action:00000 - "%s: invalid identifier" *Cause:
*Action:ORA-00911: invalid character
Everything seems to break when I try out creating a dynamic query. How do I tackle this problem? Should I continue with dynamic queries or is there an easier way to change v_dwrecord."2009"
?
Sample output: