使用MIN-Value和整列的另一列获取整行

时间:2019-01-30 17:52:11

标签: postgresql greatest-n-per-group

我有一个这样的表:

>       from    to     time   changes 
>1      A       B      40     0
>2      A       C      30     2
>3      A       D      20     1
>4      E       B      10     0

我为'to'提供了一些给定的值-例如'B'和'C'。我需要从...获取整行的MIN(time),GROUP BY

...例如:

>      from    min(time)     to  changes
>1     A       20            D   1
>2     E       10            B   0

尝试的代码如下:

"SELECT min(t.time), t.changes, t.from, t.to
    FROM table t
    GROUP BY t.from"

并尝试解决INNER JOINs的问题,但对于GROUP BY另一列而不是用于聚合的列,似乎有些棘手。

2 个答案:

答案 0 :(得分:0)

此处的汇总函数并不是最佳方法,因为然后每一列都是独立完成的(因此您可以获得min(time),但无法轻松访问该时间值所在行中的其他列)。

最直接的方法是使用distinct on,例如:

select distinct on(t.from) t.from, t.time, t.to, t.changes
from table t
order by t.from, t.time asc --ensures you get the row with the lowest t.time value for each value of t.from

这将为您从记录中的每个值和记录中的相应列值提供一行,而该记录中的时间最少为该from

答案 1 :(得分:0)

尝试此查询:

group = [first, seconds];
values = [[1,15,22][9,13,21]];
interval = [Mon, Tue, Wed];

或者这个:

SELECT a.from,
       a.time,
       a.to,
       a.changes,
FROM (
SELECT t.from,
       t.time,
       t.to,
       t.changes,
ROW_NUMBER()over(partition by t.from, order by t.time asc) as rn
FROM table t) a
WHERE a.rn = 1
相关问题