2013-05-07 22 views
1

我想用MySQL數據繪製餅圖。我需要檢索前n行並將其餘的組合在一起。
問題是第一個查詢已分組。MySQL返回第n行並將其餘的組合

SELECT name AS especie, SUM(superficie) AS superficie 
FROM ciclos 
JOIN cultivos ON id_cultivo = idcultivo 
JOIN tbl_especies ON id_especie = idespecie 
WHERE fecha_cierre IS NULL 
GROUP BY id_especie 
ORDER BY superficie DESC 

這就是我得到:

+------------+------------+ 
| Especie | Superficie | 
+------------+------------+ 
| Avena  | 50.0000 | 
| Centeno | 32.4000 | 
| Trigo  | 18.0000 | 
| Almendros | 5.1100  | 
| Olivos  | 4.7000  | 
| Vid  | 1.8300  | 
| Nogal  | 0.3500  | 
| Cerezo  | 0.2500  | 
+------------+------------+ 

而這正是我需要的:

+------------+------------+ 
| Especie | Superficie | 
+------------+------------+ 
| Avena  | 50.0000 | 
| Centeno | 32.4000 | 
| Trigo  | 18.0000 | 
| Almendros | 5.1100  | 
| Rest  | 7.1300  | 
+------------+------------+ 

在這種情況下,我需要檢索的前4行和組剩下的。

有沒有辦法用一個查詢來解決這個問題?

回答

0

解決:

我把@Gordon Linoff概念與this混吧。
@Gordon Linoff解決方案的問題在於,行號是在訂單期間添加的。

SELECT @rn := @rn + 1 AS rn, SUM(superficie) AS superficie, (CASE WHEN @rn <= 4 THEN name ELSE "Other" END) AS especie 
FROM (
    SELECT name, SUM(superficie) AS superficie 
    FROM ciclos 
    JOIN cultivos ON id_cultivo = idcultivo 
    JOIN tbl_especies ON id_especie = idespecie 
    WHERE fecha_cierre IS NULL 
    GROUP BY id_especie 
    ORDER BY superficie DESC 
) AS temp 
CROSS JOIN (SELECT @rn := 0) AS const 
GROUP BY (CASE WHEN @rn <= 4 THEN name ELSE "Other" END) 
ORDER BY superficie DESC 

希望這可以幫助別人。謝謝您的幫助。

0

你可以用一個查詢來做到這一點,但它需要一個子查詢(最終,不知何故,你必須將已分組的數據分組)。這裏有一個,MySQL專用的方式。它增加了使用可變的行的序列號,然後使用,對於分組:

select (case when rn <= 4 then especie else 'otros' end) as grouping, 
     sum(superficie) as superficie 
from (SELECT name AS especie, SUM(superficie) AS superficie, @rn := @rn + 1 as rn 
     FROM ciclos 
     JOIN cultivos ON id_cultivo = idcultivo 
     JOIN tbl_especies ON id_especie = idespecie 
     cross join (select @rn := 0) const 
     WHERE fecha_cierre IS NULL 
     GROUP BY id_especie 
     ORDER BY superficie DESC 
    ) t 
group by (case when rn <= 4 then especie else 'otros' end) 
+0

感謝您的回覆。我理解查詢,但在我附近發現了一個語法錯誤:「@rn:= 0)const WHERE ...」,我不知道爲什麼。 – 2013-05-07 03:09:20

+0

固定,CROSS JOIN內部缺少「SELECT」:CROSS JOIN(SELECT @rn:= 0)const。現在,問題是我得到前4行,但他們不是通過「superficie」命令。實際上,我需要的是將所有「超級」的「Especies」組合爲低於第四。 – 2013-05-07 05:40:48