1

Sorry in advance, I'm not exactly sure how to explain this but I am trying to do this:

I have a table that looks something like this:

id | make | model

1 | iphone | iphone 7
2 | iphone | iphone 8
3 | iphone | iphone 10
4 | samsung | galaxy note 5
5 | samsung | galaxy note 5
6 | samsung | galaxy note 4
7 | iphone | iphone 7
8 | iphone | iphone 7
9 | htc | one

I want the results to look like this:

htc | one | 1 
iphone | iphone 7 | 3 
samsung | galaxy note 5 | 2 

So essentially I only want the count for the most rows for each model while grouping both the make and the model.

Hope that makes some sort of sense to someone. Thank you in advance!

3 Answers3

1

So you want to display the model with Maximum count for each make.

Following query will just do that:

select make,model,count(*) as cnt
from phones p1
group by make,model
having cnt =  (select max(p2.cnt) 
               from 
                   (select make,model,count(*) as cnt
                          from phones
                          group by make,model
                   )p2
                where p2.make = p1.make                
               )
 ;

Click here for updated DEMO

Hope it helps!

Harshil Doshi
  • 3,497
  • 3
  • 14
  • 37
1

Do some tricks with mysql functions, you can use substring_index and group_concat:

select 
  `make`,
  substring_index(group_concat(`model` order by cnt desc), ',', 1) `model`,
  max(cnt) max_count
from (
  select `make`, `model`, count(1) cnt
  from yourtable
  group by `make`, `model`) t
group by `make`

See demo in SQLFiddle.

Some explaination:

  • Subquery t will query count of each group make, model;
  • group_concat(model order by cnt desc) with group by make will let all model be concated with separator , and order by cnt desc;
  • substring_index is a function which can split string with specified separator and return sub-string according to the index we passed.

All these functions you can check mysql official documents to learn more information.

Blank
  • 12,308
  • 1
  • 14
  • 32
0

You're probably after something like this:

SELECT a.* 
  FROM 
     ( SELECT make
            , model
            , COUNT(*) total 
         FROM my_table 
        GROUP 
           BY make
            , model
     ) a
  JOIN
     ( SELECT make
            , MAX(total) total 
         FROM 
            ( SELECT make
                   , model
                   , COUNT(*) total 
                FROM my_table 
               GROUP 
                  BY make
                 , model
          ) x 
       GROUP 
            BY make
     ) b
    ON b.make = a.make 
   AND b.total = a.total;
Strawberry
  • 33,750
  • 13
  • 40
  • 57