0

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

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   |  ...  |     ...     |  ...  |   ...

提前致谢!!

4

3 回答 3

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;

一个用于测试的 SQLfiddle

于 2013-07-17T17:38:33.423 回答
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
         ;
于 2013-07-17T17:39:27.600 回答
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
        )
        ;
于 2013-07-17T17:39:34.463 回答