我有一个名为 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/