PostgreSQL获取一列最小的行

时间:2015-07-21 16:35:17

标签: sql postgresql

今天我的第二篇PostgreSQL-Question ...我确信解决方案很简单,但我不知道该怎么做。

表I致力于:

CREATE TABLE separabilities 
  ( 
     data_bands      TEXT[] NOT NULL, 
     thematic_class1 TEXT NOT NULL, 
     thematic_class2 TEXT NOT NULL, 
     jm_dist         DOUBLE PRECISION NOT NULL 
  ) 

我的查询:

select sep.data_bands,
       sum(sep.jm_dist)/count(sep.data_bands) as avarage_jm_dist, 
       min(jm_dist)
from separabilities as sep
group by sep.data_bands
order by avarage_jm_dist

我得到了什么: result subset

我需要什么:

另外两个列,包含与最小距离对应的主题类。

喜欢那样: data_bands - avarage_jm_dist - min - thematic_class1 - thematic_class2

1 个答案:

答案 0 :(得分:1)

像这样。

SELECT * 
FROM   (SELECT Row_number()OVER(partition BY data_bands ORDER BY jm_dist) AS RN, 
               data_bands, 
               thematic_class1, 
               thematic_class2
               Avg(sep.jm_dist)OVER(partition BY data_bands) as avarage_jm_dist
               jm_dist  
        FROM   separabilities) A 
WHERE  rn = 1 

或者您需要将结果加入主表以获取min jm_distdata_bands

的thematic_class1和thematic_class2
SELECT * 
FROM   separabilities A 
       INNER JOIN (SELECT sep.data_bands, 
                          Sum(sep.jm_dist) / Count(sep.data_bands) AS avarage_jm_dist
                          Min(jm_dist)                             AS jm_dist 
                   FROM   separabilities AS sep 
                   GROUP  BY sep.data_bands) B 
               ON A.data_bands = B.data_bands 
                  AND A.jm_dist = B.jm_dist 
ORDER  BY avarage_jm_dist