sql - PostgreSQL SQL : Find single arbitrary tuple from each id

标签 sql postgresql

考虑下表:

 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有一个任意元组,以及相应的xy值。以下结果是正确的:

 id | x  |  y  
----+----+-----
  1 | 10 | 100
  2 | 20 | 130
  3 | 20 | 130

或者:

 id | x  |  y  
----+----+-----
  1 | 30 | 130
  2 | 30 | 130
  3 | 20 | 130

idxy 在任何上下文中都不是唯一的。

如何在 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 unless ORDER 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/

相关文章:

postgresql - 如何在 PostgreSQL 8.4 中导入现有的 *.sql 文件?

spring - 如何在 r2dbc-postgresql 中使用 EnumCodec

mysql - 将 bool 值设置为 mysql 记录指示在所选时间戳范围之前是否存在其他记录

mysql - 嵌套的 MySQL 查询

MySQL 一对多从日期子选择最大 UNIX_TIMESTAMP()

python - 按列分组以在 Postgresql 中获取数组结果

postgresql - 安装在特定计算机上的 PostgreSQL 数据库表的说明

python - 如何测量 Django 缓存性能?

.net - Linq like 跨多个领域搜索

c# - 当我在文本框中键入 RowFilter 时出现语法错误