我的表是
id position some data
---|--------|------------|
1 | 1 | data |
1 | 2 | data |
2 | 1 | data |
2 | 2 | data |
5 | 1 | data |
5 | 2 | data |
5 | 3 | data |
我如何将其格式化为以下内容。这样它只显示具有最高位置的唯一ID,如下所示。数据是经度和纬度,因此它应该只返回最高位置long和lat。
id position some data
---|--------|------------|
1 | 2 | data |
2 | 2 | data |
5 | 3 | data |
答案 0 :(得分:1)
您可以加入最大分组的集合;
select *
from the_table inner join (
select id, max(position) as max_pos
from the_table
group by id
) as T on the_table.id = T.id and the_table.position = T.max_pos
order by the_table.id
答案 1 :(得分:-1)
假设数据适当地响应聚合,您可以这样做:
SELECT id, MAX(position), MAX(some_data)
FROM My_Table
GROUP BY id
如果没有,我相信该版本具有必要的OLAP功能:
WITH Max_Data as (SELECT id, position, data,
ROW_NUMBER() OVER(PARTITION BY id
ORDER BY position DESC) as rowNum
FROM My_Table)
SELECT id, position, data
FROM Max_Data
WHERE rowNum = 1
您需要一个包含position
的索引才能获得最佳效果。
答案 2 :(得分:-2)
SELECT id, MAX(position), data
FROM yourtable
GROUP BY id
确定id
字段是您的memberid
。这将获取每个id
的最大位置。但是,数据是另一回事。您是否需要与MAX(位置)相同的记录中的实际数据,或者只需要任何数据?
如果您需要它来自与最大ID相同的记录中的数据,那么
SELECT yourtable.id, yourtable.position, yourtable.data
FROM yourtable
LEFT JOIN (
SELECT id, MAX(position) AS position
FROM yourtable AS child
GROUP BY id
) AS child ON (yourtable.id = child.id AND yourtable.position = child.position