1
SELECT
    user_id,
    count(*) total,
    sum(case when type = 'yes' then 1 else 0 end) as type_1,
    sum(case when type = 'no' then 1 else 0 end) as type_2
FROM history
GROUP by user_id

How get TOP 100 rows from this query which have max count type = 'yes' ?

3 Answers3

1

You can use LIMIT to limit the number of results and use an ORDER BY to order it so the results are in descending order of total.

SELECT
    user_id,
    count(*) total,
    sum(case when type = 'yes' then 1 else 0 end) as type_1,
    sum(case when type = 'no' then 1 else 0 end) as type_2
FROM history
GROUP by user_id
ORDER BY type_1 DESC
LIMIT 100
rharvey
  • 1,987
  • 1
  • 28
  • 23
0

You should add WHERE statement to your query to add conditional statement Also, I can see that you are using mysql, so that means you should order your data by argument descending and limit result to 100

    SELECT
        user_id,
        count(*) total,
        sum(case when type = 'yes' then 1 else 0 end) as type_1,
        sum(case when type = 'no' then 1 else 0 end) as type_2
    FROM history
    WHERE type='yes'
    GROUP by user_id
    ORDER BY total DESC
    LIMIT 100 
Alexander Capone
  • 528
  • 3
  • 16
0
SELECT
    user_id,
    count(*) total,
    sum(case when type = 'yes' then 1 else 0 end) as type_1,
    sum(case when type = 'no' then 1 else 0 end) as type_2
FROM history
GROUP by user_id
ORDER by type_1 DESC
LIMIT 100
  • While this code may answer the question, providing additional context regarding _why_ and/or _how_ it answers the question would significantly improve its long-term value. Please [edit] your answer to add some explanation. – Toby Speight Apr 01 '16 at 15:06
  • @TobySpeight im not understand, tell me please what some explanation need add? – user6129461 Apr 02 '16 at 08:01