2012-07-24 115 views
0

我有以下查詢:SUM()COUNT()列在MySQL

SELECT COUNT(employees.id) AS emp_count 
FROM `orders` 
INNER JOIN `companies` ON `companies`.`id` = `orders`.`company_id` 
INNER JOIN employees ON employees.company_id = companies.id 
    AND (employees.deleted_at >= companies.activate_at OR employees.deleted_at IS NULL)      
    AND employees.created_at <= companies.activate_at 
WHERE 
    (companies.activate_at BETWEEN '2012-01-31 23:00:00' AND '2012-02-29 22:59:59'      
    AND orders.type = 'Order::TrialActivation' 
    AND orders.state = 'completed') 

我需要所有的 「emp_count」 列的總和。目前,我遍歷上述查詢返回的所有行,然後遍歷Ruby中的「emp_count」。但是有很多行,所以這佔用了很多內存。

我如何SUM在SQL中的「emp_count」並返回這個數字?

+0

你爲什麼要服用其他數據?我的意思是:你得到的數據,你會得到你正在尋找的數額。它將如何以及在哪裏出現? – 2012-07-24 17:43:07

+0

這是模糊的,從上面刪除。感謝您指出。 – skinkelynet 2012-07-24 17:44:43

+3

我不太明白這個問題。無論如何,這個查詢只返回一行,一列emp_count no?沒有「GROUP BY」或任何東西 – mask8 2012-07-24 17:50:59

回答

1

---更新:---

既然問題已經更新,我會更新我的答案:

如果你正在嘗試只是從你的查詢中獲取的行數基於WHERE語法,那麼你可以使用COUNT()。但是,如果您想要查詢中的所有employees.id值的總和,請將COUNT(employees.id)更改爲SUM(employees.id),並且應該按照您的要求進行操作。

---原來的答案---

嘗試使用子查詢,還挺像這樣(代碼未測試):

SELECT SUM(x.emp_count) FROM (
    SELECT COUNT(employees.id) AS emp_count 
    FROM `orders` 
    INNER JOIN `companies` ON `companies`.`id` = `orders`.`company_id` 
    INNER JOIN employees ON employees.company_id = companies.id 
     AND (employees.deleted_at >= companies.activate_at OR employees.deleted_at IS NULL)      
     AND employees.created_at <= companies.activate_at 
    WHERE 
     (companies.activate_at BETWEEN '2012-01-31 23:00:00' AND '2012-02-29 22:59:59'      
     AND orders.type = 'Order::TrialActivation' 
     AND orders.state = 'completed') 
) x; 

您可以在MySQL documentation瞭解更多關於子查詢和另請參閱:How to SUM() multiple subquery rows in MySQL?