sql - 在显示所有其他列时,在同一查询中使用 MIN 值分组

标签 sql postgresql

我有一个名为 a 的 View ,其中包含以下数据:

 ID    tDate        name     task   val
23   2015-06-14
23   2015-06-25
126  2015-06-18
126  2015-06-22
126  2015-06-24

ID 为整数,tDate 为时间戳。

基本上我想为每个 ID 获取 tDate 的最小值并显示这一行。 含义:

ID   tDate       name     task   val
23   2015-06-14
126  2015-06-18

我写了这个查询:

select ID, min(tDate)
from a
group by ID
order by ID

这是可行的但是它不允许我显示a 的所有其他列

例如,如果我这样做:

select ID, min(tDate), name
from a
group by ID
order by ID

它说名称必须在分组依据下。所以我写了这个查询:

select ID, MIN(tDate), name, task, val , ....
from a
group by ID, name, task, val , ....
order by ID

而这个不起作用。它给出了错误的结果。

如何解决?

最佳答案

对于这类问题,Postgres 有非常方便的distinct on:

select distinct on (id) a.*
from a
order by id, tdate;

这将为每个 id 返回一行。该行是由 order by 子句中定义的顺序确定的第一行。

关于sql - 在显示所有其他列时,在同一查询中使用 MIN 值分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31119635/

相关文章:

django - Postgres : prioritize main application over background celery jobs

sql - Postgresql查询建议

sql - 无数据的物化 View 仍在加载数据

sql - 是否可以防止 ORDS 转义我的 GeoJSON?

sql - SQL在WHERE子句之后选择最小值

mysql - MySQL 中的 OUTPUT 子句

postgresql - 在 Postgres 中,pg_stat_database.xact_commit 到底是什么意思?

postgresql - 获得正确的周数

mysql - SQL B在A中出现了多少次

sql - SQL Server 中范围变量的范围