2014-02-11 4 views
0

아래 쿼리를 사용하여 mysql 데이터베이스에서 데이터를 가져옵니다.MySQL 쿼리 제한 함수

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

결과적으로 거의 100+ 행이 늘어납니다.

지금 내가

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

다음과 같이 쿼리를 수정 만 상위 25 components.so를 표시하고자하지만 난 내가 필요한 것은 '로 태그되어야하는 구성 요소의 상위 25 개 항목과 나머지를 표시하는 것입니다 기타 '를 수량 번호와 함께 사용합니다.

결과 집합에 아래 내용이 비슷합니다.

Item1 123 
Item2 112 
.... 
.... 
Item25 24 
Others 156 
+0

'기타'줄에 '156'이 무엇입니까? 다른 행의 번호입니까? – Barmar

+0

예, 나머지 구성 요소 번호. – CarlJohn

답변

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 
1

또한 ROW_NUMBER를 사용하여 시도 할 수 있습니다.

SELECT component,sum(quantity) FROM(
SELECT @rn:[email protected]+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