This question already has answers here:
Select first row in each GROUP BY group?

(17个答案)


4年前关闭。




我有这张 table :
+----+-----+----------+
| id | name| key      |
+----+-----+----------+
| 1  | foo |111000    |
| 2  | bar |111000    |
| 3  | foo |000111    |
+----+-----+----------+

有没有一种方法可以通过 key 分组来获得此结果?
+----+-----+----------+
| id | name| key      |
+----+-----+----------+
| 2  | bar |111000    |
| 3  | foo |000111    |
+----+-----+----------+

或此结果:
+----+-----+----------+
| id | name| key      |
+----+-----+----------+
| 1  | foo |111000    |
| 3  | foo |000111    |
+----+-----+----------+

如果我使用此查询:
SELECT * FROM sch.mytable GROUP BY(key);

我知道这是不正确的,因为我应该按需要显示的所有列进行分组。

有解决这个问题的方法吗?

最佳答案

distinct on

select distinct on (key) *
from t
order by key, name

注意order by子句确定哪一行将赢得平局。

关于sql - 选择所有GROUP BY一列的列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39816069/

10-16 16:17