Oracle SQL 返回行相同的最大值
Oracle SQL returning rows same max value
这是我的 table
------------------
|__fruit__|_color_|
| banana | yellow|
| lemon | yellow|
| apple | red |
| cherry | red |
| lime | green |
查询的输出应该是:
yellow, banana
yellow, lemon
red, apple
red, cherry
我想要 return 颜色数量最多的水果。由于红色和黄色都具有相同的最大颜色量,因此我无法同时获得它们。
我尝试过使用 distinct
关键字,以及使用 count
尝试不同的聚合函数,但只能 return 一种颜色。
您必须 group by
颜色并 join
到原始 table 以获得所需的结果。
with cnts as (select color,count(*) as cnt
from tablename
group by color)
, maxcnt as (select max(cnt) as mxcnt from cnts)
select t.color,t.fruit
from cnts c join maxcnt m on c.cnt = m.mxcnt
join tablename t on t.color = c.color
这是我的 table
------------------
|__fruit__|_color_|
| banana | yellow|
| lemon | yellow|
| apple | red |
| cherry | red |
| lime | green |
查询的输出应该是:
yellow, banana
yellow, lemon
red, apple
red, cherry
我想要 return 颜色数量最多的水果。由于红色和黄色都具有相同的最大颜色量,因此我无法同时获得它们。
我尝试过使用 distinct
关键字,以及使用 count
尝试不同的聚合函数,但只能 return 一种颜色。
您必须 group by
颜色并 join
到原始 table 以获得所需的结果。
with cnts as (select color,count(*) as cnt
from tablename
group by color)
, maxcnt as (select max(cnt) as mxcnt from cnts)
select t.color,t.fruit
from cnts c join maxcnt m on c.cnt = m.mxcnt
join tablename t on t.color = c.color