Question

I have a database with many individuals. Each individual has observations for many quarte

`
+----+---------+--------+--------+
| az | quarter | imp    |year
+----+---------+--------+--------+
|  1 | 1.2012  |      6 |  2012  |
|  1 | 2.2012  |      5 |  2012  |
|  1 | 3.2012  |      5 |  2012  |
|  1 | 4.2012  |      5 |  2012  |
|  2 | 1.2012  |      3 |  2012  |
|  2 | 2.2012  |      3 |  2012  |
|  2 | 3.2012  |      4 |  2012  |
|  2 | 4.2012  |      3 |  2012  |
|....|  ....   |        |
+----+---------+--------+-------+
`

I need to create a column that has for each year the sum of the quarters

+----+---------+--------+--------+
| az | year    | imp    |imp.year
+----+---------+--------+--------+
|  1 |   2012  |      6 |  21    
|  1 |   2012  |      5 |  21
|  1 |   2012  |      5 |  21
|  1 |   2012  |      5 |  21
|  2 |   2012  |      3 |  13
|  2 |   2012  |      3 |  13
|  2 |   2012  |      4 |  13
|  2 |   2012  |      3 |  13
|....|  ....   |        |
+----+---------+--------+-------+

I used

CREATE TABLE IMP_TOT_YEAR AS SELECT
az, year, SUM(imp) as imp.year,
FROM IMP_TOT
GROUP BY az,year;

then

CREATE TABLE complete AS SELECT
a.*, b.imp.year,
FROM IMP_TOT as a
left join IMP_TOT_YEAR as b 
on a.az=b.az and a.anno=b.year ;

I have more than 10 variables like imp and many years so the join is too slow. It's running from more than 2 hours. I was looking for a method without join like:

if quarter=1.2012 then imp.year = imp in (actual_row+1)+imp in (actual_row+2)+imp in (actual_row+3)

else imp.year = imp.year in (actual_row -1)

So I don't need to esecute subquery or join. Is it possible?

Was it helpful?

Solution

The join should be fine if you add indexes to IMP_TOT_YEAR:

create index IMP_TOT_YEAR_az_yr on IMP_TOT_YEAR(az, yr);

It sounds like you have a lot of data, so using an intermediate table might be fast.

On the other hand, if you want to do it in one table, be sure you have an index on IMP_TOT(az, yr) and try:

SELECT t.*,
       (SELECT SUM(imp) as imp.year,
        FROM IMP_TOT t2
        WHERE t2.az = t.az and t2.yr = t.yr
       ) as YearTot
FROM IMP_TOT;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top