0

Here is my table

 ------------------
|__fruit__|_color_|
| banana  | yellow|
| lemon   | yellow|
| apple   |  red  |
| cherry  |  red  |
| lime    | green |    

The output from the query should be:

yellow, banana
yellow, lemon
red, apple
red, cherry

I'm wanting to return the fruit with the maximum amount of the count of color. Since both the color red and the color yellow have the same maximum amount of color, I havent been able to get them both. I have tried using distinct keywords, as well as trying different aggregate functions using count but have only been able to return one color.

1
  • Kindly share what you have tried so far. Commented Sep 19, 2015 at 22:57

1 Answer 1

1

You have to group by color and join it to the original table to get the desired result.

Fiddle

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
Sign up to request clarification or add additional context in comments.

2 Comments

The edited version only returns red and not yellow, and is much more confusing for a beginner.
the earlier version..was explicitly returning all rows where count was > 1. However, with the modified version, you get only rows for colors where there is a maximum count, which was your question. Also, i added more rows in the fiddle for your understanding

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.