每组最大值的行 - SQLite

时间:2018-01-18 17:19:24

标签: sqlite

如果某个表columns(name, lat, lon, population, type),其中每个名称有很多行,我想选择按名称分组的行,其中人口是最高的。如果我将自己限制在名称和人口

,则以下情况有效
SELECT name, Max(population) 
FROM table WHERE name IN ('a', 'b', 'c') 
GROUP BY name;

但我想要其他列 - lat, lon, type - 以及结果。如何使用SQLite实现这一目标?

2 个答案:

答案 0 :(得分:3)

SQLite允许你to just list the other columns you want;保证它们来自具有最大值的行:

SELECT name, lat, lon, Max(population), type
FROM table
WHERE name IN ('a', 'b', 'c')
GROUP BY name;

答案 1 :(得分:1)

加入反对该结果以获取完整的表记录

SELECT t1.*
FROM your_table t1
JOIN 
(
    SELECT name, Max(population) as max_population
    FROM your_table 
    WHERE name IN ('a', 'b', 'c') 
    GROUP BY name
) t2 ON t1.name = t2.name
    and t1.population = t2.max_population