Skip to content

Instantly share code, notes, and snippets.

@carymrobbins
Created September 30, 2013 15:58
Show Gist options
  • Save carymrobbins/6765954 to your computer and use it in GitHub Desktop.
Save carymrobbins/6765954 to your computer and use it in GitHub Desktop.
PostgreSQL - Group By Primary Key Bug
-- 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