2014-02-11 117 views
0

我正在使用下面的查詢從mysql數據庫中獲取數據。MySQL查詢 - 限制函數

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

因爲我得到了幾乎100多行。

現在我想只顯示前25 components.so我修改查詢,如下

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

但我什麼,我需要的是顯示排名前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