Select all columns with GROUP BY one column
本问题已经有最佳答案,请猛点这里访问。
我有这张桌子:
1 2 3 4 5 6 7 | +----+-----+----------+ | id | name| KEY | +----+-----+----------+ | 1 | foo |111000 | | 2 | bar |111000 | | 3 | foo |000111 | +----+-----+----------+ |
有没有办法按键分组才能得到这个结果?
1 2 3 4 5 6 | +----+-----+----------+ | id | name| KEY | +----+-----+----------+ | 2 | bar |111000 | | 3 | foo |000111 | +----+-----+----------+ |
或者这个结果:
1 2 3 4 5 6 | +----+-----+----------+ | id | name| KEY | +----+-----+----------+ | 1 | foo |111000 | | 3 | foo |000111 | +----+-----+----------+ |
如果我使用此查询:
1 | SELECT * FROM sch.mytable GROUP BY(KEY); |
这是不正确的我知道,因为我应该按照我需要显示的所有列进行分组。
有这个问题的解决方案吗?
适用于所有数据库引擎的查询
1 2 3 4 5 6 7 8 | SELECT t1.* FROM sch.mytable t1 JOIN ( SELECT MIN(id) AS id FROM sch.mytable GROUP BY KEY ) t2 ON t1.id = t2.id |
其中
不同的
1 2 3 | SELECT DISTINCT ON (KEY) * FROM t ORDER BY KEY, name |
请注意,