2014-09-30 86 views
0

我正在計算一個在餅圖中顯示的東西。我只想用實際的投資類型顯示最高的6個計數,其餘的顯示爲投資類型「其他」。限制計數並將剩餘部分設置爲「其他」

SELECT i.investment_type AS investmentType, 
     COUNT(*) AS investmentCount 
    FROM investment i, 
     vertical v 
WHERE v.vertical_name = i.investment_type 
    AND v.type = 'STR' 
    AND i.status_funding = 'o' 
GROUP 
    BY i.investment_type 
ORDER 
    BY investmentCount desc 

上面的查詢給了我一個結果

enter image description here

通過添加limit 6到查詢我得到

enter image description here

我需要的是一個更加一行investmentType「其他「和investmentCount」7「。

+0

你正在使用什麼樣的SQL? MSSQL,MySQL,PostgreSQL,SQLite ......?所有這些系統之間有一些變化。 (你也應該把它添加到你的問題的標籤) – personne3000 2014-09-30 07:15:01

+0

MySQL.Sorry。也會添加該標籤。 – puppuli 2014-09-30 07:17:42

+0

@പുപ്പുലി..你有沒有嘗試子查詢? – 2014-09-30 07:20:25

回答

1

,你可能覺得像有一個嘗試:

SELECT i.investment_type as investmentType,COUNT(*) as investmentCount FROM investment i,vertical v 
    WHERE v.vertical_name =i.investment_type AND v.type='STR' AND i.status_funding ='o' 
    group by i.investment_type order by investmentCount desc 
    limit 6 
UNION 
    SELECT "others" as investmentType, SUM(othersInvestmentCount) as investmentCount FROM (
     SELECT COUNT(*) as othersInvestmentCount FROM investment i,vertical v 
     WHERE v.vertical_name =i.investment_type AND v.type='STR' AND i.status_funding ='o' 
     group by i.investment_type order by investmentCount desc 
     limit 6, 4294967296 
    ) 

我沒有測試此查詢,你可以,如果你發現語法問題,對其進行編輯。涉及三個實際的查詢,但它不應該是瘋狂的緩慢(如果不需要更快的速度,那麼不需要更快地嘗試)。

我假設你的數據庫中有少於2^32條記錄,這對於MySQL數據庫來說似乎是一個非常合理的假設(但如果你覺得不安全,就用2^64代替它)。