考虑下表:
id | x | y
----+----+-----
1 | 10 | 100
1 | 20 | 120
1 | 30 | 130
2 | 10 | 130
2 | 20 | 130
2 | 30 | 130
3 | 20 | 130
(7 rows)
我希望每个id
有一个任意元组,以及相应的x
和y
值。以下结果是正确的:
id | x | y
----+----+-----
1 | 10 | 100
2 | 20 | 130
3 | 20 | 130
或者:
id | x | y
----+----+-----
1 | 30 | 130
2 | 30 | 130
3 | 20 | 130
id
、x
和 y
在任何上下文中都不是唯一的。
如何在 SQL 中解决这个问题(在 PostgreSQL
下)?可能有数百万个 id
。
更新:
谢谢,@Lukáš Lalinský。引用您链接到的 PostgreSQL 文档:
DISTINCT ON
( expression [, ...] ) keeps only the first row of each set of rows where the given expressions evaluate to equal... Note that the "first row" of each set is unpredictable unlessORDER BY
is used to ensure that the desired row appears first.
最佳答案
使用DISTINCT ON
子句应该完成这项工作:
SELECT DISTINCT ON (id) id, x, y FROM table
关于sql - PostgreSQL SQL : Find single arbitrary tuple from each id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7379233/