I’m having an issue with a query, I’m using postgresql 9.2.
I have created a view which returns a key value, a timestamp, and an interval that look like this:
select * from foo.a; -- My view and the results
k | ts1 | tm
1 | 2011-12-08 06:46:00+00 | 01:00:00
1 | 2011-12-08 09:14:00+00 | 01:00:00
2 | 2011-12-08 02:00:00+00 | 02:00:00
2 | 2011-12-08 05:00:00+00 | 02:00:00
4 | 2011-12-08 10:06:00+00 | 02:00:00
4 | 2011-12-08 13:31:00+00 | 02:00:00
1 | 2011-12-11 03:00:00+00 | 01:00:00
1 | 2011-12-11 04:49:00+00 | 02:00:00
4 | 2011-12-11 10:06:00+00 | 02:00:00
4 | 2011-12-11 13:31:00+00 | 02:00:00
I have about 8,000 rows in my results. Now, I want to sum the interval’s and group by key, so I do this:
select k,
sum(tm) as tm
from foo.a
group by k;
As expected my results are:
k | tm
1 | 5:00
2 | 4:00
4 | 8:00
I want to take it a step further and do this (the error – ERROR: subquery uses ungrouped column ‘ts1’ from outer query).
select k,
sum(tm) as tm,
(select sum(tm) where ts1 > '2011-12-09')
-- (select sum(tm) where ts1 > '2012-01-01')
-- I need to the above on 5 different dates.
from foo.a
group by k,
Desired results are:
k | tm | tm1
1 | 5:00 | 3:00
2 | 4:00 |
4 | 8:00 | 4:00
If I add ts1 into my group clause, it doesn’t return desired results, naturally – because I don’t want to group by ts1, only k. I can use ts1 in an aggregate function and the query will run with undesirable results.
This works:
select foo.a.k,
bar.tm1,
sum(tm)
from foo.a
left join
(select k,
sum(tm) as tm1
from foo.a
where foo.a.ts1 > '2011-12-09'
group by k) as bar
on foo.a.k = bar.k
group by foo.a.k,
bar.tm1;
But querying the same view for the same information seems wrong and unnecessary. Especially, since I have to do this 5 times.
My question: Is there a work-around for performing a correlated-query on an ungrouped column? If not, what is a better approach to achieving my desired results?
Is this what you want?