簡體   English   中英

使用MySQL GROUP BY,如何控制在非聚合列中選擇的默認值?

[英]With a MySQL GROUP BY, how do I control the default value to choose in non-aggregated columns?

我有下表:

type |     description  | rank
------------------------|-------
1    | "foo bar baz"    | 1
1    | "bar foo baz"    | 4
2    | "baz bar foo"    | 2
3    | "bar baz foo"    | 3

我想要GROUP BY type ,對於所有其他列,返回與MAX(rank)關聯的值。 顯然MAX(rank)很容易,但我怎么得到"description ORDER BY rank DESC"

您必須選擇max(rank)和self-join來獲取相關描述

select t1.type, t1.max_rank, t2.description from (
    select max(rank) max_rank, type
    from mytable
    group by type
) t1 join mytable t2 on t1.type = t2.type and t1.max_rank = t2.rank
order by t1.max_rank desc

或使用not exists

select * from mytable t1
where not exists (
    select 1 from mytable t2
    where t2.type = t1.type
    and t2.rank > t1.rank
)
order by rank desc

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM