postgresql从两列的值对中选择最小值

时间:2013-07-17 17:30:32

标签: postgresql select distinct

我有一个看起来像这样的表:

id | group | title | description | added | modified
---------------------------------------------------
1  |   1   |  ...  |     ...     |  ...  |   ...
2  |   1   |  ...  |     ...     |  ...  |   ...
3  |   2   |  ...  |     ...     |  ...  |   ...
4  |   2   |  ...  |     ...     |  ...  |   ...
5  |   3   |  ...  |     ...     |  ...  |   ...

现在我需要选择每个组值的第一行。我认为使用DISTINCT关键字是一种正确的方向。但是使用:

SELECT DISTINCT group FROM table;

显然只返回组值,但不返回其余字段:

group
-----
  1
  2
  3

有谁知道如何做到这一点?

我正在寻找的是 - 就上面的例子而言 - 这种输出:

id | group | title | description | added | modified
---------------------------------------------------
1  |   1   |  ...  |     ...     |  ...  |   ...
3  |   2   |  ...  |     ...     |  ...  |   ...
5  |   3   |  ...  |     ...     |  ...  |   ...

提前致谢!!

3 个答案:

答案 0 :(得分:2)

您可以使用类似的内容;

SELECT "id", "group", "title", "description", "added", "modified"
FROM (
  SELECT *,ROW_NUMBER() OVER (PARTITION BY "group" ORDER BY "id") rn
  FROM Table1
) this_could_be_called_anything
WHERE rn=1;

An SQLfiddle to test with

答案 1 :(得分:0)

试试这个:

    select t.*
      from table t
inner join (
                select min(te.id)   id_pivot
                     , te.grp
                  from table te
              group by te.grp 
           ) tg
        on tg.id_pivot = t.id
         ;

答案 2 :(得分:0)

SELECT mk.* FROM meuk mk
JOIN ( SELECT zgroup, MIN(id) AS id
        FROM meuk
        GROUP BY zgroup
        ) agg ON agg.id = mk.id
        ;

或者这个:

SELECT * FROM meuk mk
WHERE NOT EXISTS ( SELECT  *
        FROM meuk nx
        WHERE nx.zgroup = mk.zgroup
        AND nx.id < mk.id
        )
        ;