Created
September 30, 2013 15:58
-
-
Save carymrobbins/6765954 to your computer and use it in GitHub Desktop.
PostgreSQL - Group By Primary Key Bug
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Test Data | |
drop table if exists x, y, z; | |
create temporary table x(id serial primary key, a int); | |
insert into x(a) values (1), (2); | |
create temporary table y(id serial primary key, x_id int, b int); | |
insert into y(x_id, b) values (1, 1), (2, 2), (3, 3); | |
create temporary table z(id serial primary key, x_id int, c int); | |
insert into z(x_id, c) values (1, 3), (1, 4), (2, 5); | |
-- Example - unable to group by primary key from subquery | |
with cte as ( | |
select x.id as x_id, x.a, sum(y.b) as sum_b | |
from x | |
join y | |
on (x.id = y.x_id) | |
group by x.id | |
) | |
select cte.*, sum(z.c) as sum_c | |
from cte | |
join z | |
on (cte.x_id = z.x_id) | |
group by cte.x_id; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment