0

I'm using the below query to get datas from mysql database.

select component,count(component) as Quantity from mfgGroup where 
 period between '2013-01-01' and '2013-12-31'

I'm getting almost 100+ rows as a result.

Now i want to display only top 25 components.so I modified the query as below

select component,count(component) as Quantity from mfgGroup where 
period between '2013-01-01' and '2013-12-31' limit 0,25

But i what i need is to display the top 25 items and rest of the components should be tagged as 'Others' with the quantity numbers.

Like these below in the resultset.

Item1 123
Item2 112
....
....
Item25 24
Others 156
2
  • What is 156 in the Others line? Is it the number of other rows? Commented Feb 11, 2014 at 7:37
  • yeah, the rest of the components number. Commented Feb 11, 2014 at 7:39

2 Answers 2

3
SELECT component, COUNT(*) AS Quantity
FROM mfgGroup
WHERE period between '2013-01-01' and '2013-12-31'
GROUP BY component
ORDER BY Quantity DESC
LIMIT 25

UNION

SELECT 'Others', COUNT(*) c
FROM mfgGroup g
LEFT JOIN (
    SELECT component, COUNT(*) AS Quantity
    FROM mfgGroup
    WHERE period between '2013-01-01' and '2013-12-31'
    GROUP BY component
    ORDER BY Quantity DESC
    LIMIT 25
) top25
ON g.component = top25.component
WHERE top25.component IS NULL
AND period between '2013-01-01' and '2013-12-31'
HAVING C > 0
Sign up to request clarification or add additional context in comments.

Comments

1

You can try using row_number also.

SELECT component,sum(quantity) FROM(
SELECT @rn:=@rn+1 AS rank, IF(@rn>25,"Others",component) component, Quantity
FROM (
    SELECT component, COUNT(*) AS Quantity
    FROM mfgGroup
    WHERE period between '2013-01-01' and '2013-12-31'
    GROUP BY component
    ORDER BY Quantity DESC
) t1, (SELECT @rn:=0) t2
) temp
GROUP BY component

Comments

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.