2011-07-14 48 views
2

我有一個MySQL查詢,其中計數小時,我們從我們的客戶的前五名工作。這工作正常,我正在圖上繪製數據。我試圖實現的是在查詢中進行計算,返回第六個結果集,它是不在前五名的所有小時數的總和。即「其他」結果,以便所有6個結果的總和等於項目總和的總和。MySQL計數所有外部限制

我的查詢:在應用程序的all_hours

SELECT 
    SUM(projects.hours) AS total_hours 
FROM projects 
GROUP BY projects.companyID 
ORDER BY total_hours DESC 
LIMIT 5 

回答

4
SELECT 
SUM(projects.hours) AS total_hours, 
(SELECT SUM(projects.hours) FROM projects) AS all_hours 
FROM 
projects 
GROUP BY 
projects.companyID 
ORDER BY total_hours DESC 
LIMIT 5 

減total_hours。

+0

+1這個簡單直接的方法爲了使它稍微簡單直接一些,你可以指定'total_hours'和'all_hours'分配給用戶定義的變量,並在SQL語句中執行減法。 – Mike

0
SELECT 
    1 no, 
    projects.company, 
    SUM(projects.hours) AS total_hours 
FROM 
    projects 
GROUP BY 
    projects.companyID 
ORDER BY 
    total_hours DESC 
LIMIT 5 

UNION ALL 

SELECT 
    2 no, 
    'Others', 
    SUM(projects.hours) AS total_hours 
FROM 
    projects 
WHERE projects.companyID NOT IN 
(SELECT companyID 
    FROM 
    ( SELECT 
     projects.companyID 
    FROM 
     projects 
    GROUP BY 
     projects.companyID 
    ORDER BY 
     SUM(total_hours) DESC 
    LIMIT 5 
) AS tmp 
) 
+0

輝煌。謝謝。只是一個簡單的問題,「1不」和「2不」是做什麼的? – Joseph

+0

@Joseph,如果允許您知道哪些行來自查詢的第一部分以及來自第二部分的哪些行。 – Johan

+0

@Johan,還有一點額外的東西。我還爲前5名中的每個人選擇了projects.company_name。我如何將它設置爲第二個查詢的「其他」? – Joseph

0

如何這兩種方法的結合,增加一個彙總,我們可以刪除不需要的IN

(我不知道,如果你能rolluplimit雖然,我沒有MYSQL這裏,所以無法測試,抱歉)

注:我希望它可以返回NULL的企業ID包含其他行的總數,

SELECT companyID, 
CASE WHEN companyID IS NULL THEN 
    sum(Total_hours) 
ELSE 
    sum(Total_hours) * -1 
END 

FROM 
(   
    SELECT companyID,SUM(projects.hours) AS total_hours, 
    FROM projects 
    GROUP BY projects.companyID 
    ORDER BY total_hours DESC WITH ROLLUP LIMIT 5 
    UNION ALL 
    SELECT null,SUM(projects.hours)*-1 total_hours FROM projects 
) 
GROUP BY companyID