[英]Select Row with highest value between two tables while also selecting other columns in group by
[英]Selecting only the highest value for a specific record with other unique columns?
我有包含類似於以下數據的表。 我需要的查詢將導致Orange和Apple具有最高cityID值的最高結果。
id | fruit | attr | cityID | personID
163 Apple green 3685 235
163 Apple red 3145 267
163 Apple yellow 1522 560
164 Orange big 1344 147
164 Orange small 833 2673
我需要的結果是
id | fruit | attr | cityID | personID
163 Apple green 3685 235
164 Orange big 1344 147
我開始嘗試用
select
fruit_id,
fruit,
attr,
max(cityID),
personID
from fruits_cities
group by
fruit_id,
fruit,
attr,
max(cityID),
personID
這是一個挑戰。 您需要使用某種比較。 這是一個簡單的方法:
select fc.*
from fruits_cities fc
where fc.cityId = (select max(CityId)
from fruits_cities fc2
where fc2.fruit_id = fc.fruit_id
);
最短的代碼可能會對您有所幫助。
SELECT fruit_id,fruit,attr,max(cityID),personID FROM `fruits_cities` GROUP BY fruit ORDER BY fruit_id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.