SQL: Group by attributes from one table but not the other in a join?

时间:2015-10-30 22:31:01

标签: sql postgresql

Essentially I have 2 tables joined which I need to group by the attributes in the first table, but not the second.

I can do this...

SELECT "Table1".*

...to produce only the columns from the first table in the output. But the following results in an error when trying to group them...

GROUP BY "Table1".*

Is there a way to group them by the elements in the first table without typing all the individual columns in Table1?

2 个答案:

答案 0 :(得分:1)

Postgres supports an ANSI feature called functional dependency. So, if you have a unique id in table1, then you can aggregate by that:

select t1.*
from table1 t1
group by t1.id;

The id has to be declared correctly as either a primary key or unique key.

答案 1 :(得分:1)

You can use SELECT DISTINCT to remove duplicate data

SELECT DISTINCT "Table1".*