2016-01-08 63 views
0

我希望有人能幫助我解決這個問題,我一直在嘗試不同的組合,但似乎無法得到正確的結果。子查詢不輸出正確的結果?

首先,我有3個表,類別,部門和主人,主人有FK。我想得到每個部門的總時間總和和部門類別總時間總和,以便我可以看到哪個部門有多少時間用於該類別,都應該按部門分組並且按正確的順序?

我可以得到結果,但不出來吧,這裏是我的代碼...

SELECT a.department, time_spent , COUNT(DISTINCT (a.department)), sum_quarantine FROM 

    (SELECT d.department, SUM(time_spent) as time_spent 
    FROM master as m 
    INNER JOIN department as d ON d.dept_id = m.dept_id GROUP BY d.department) AS a, 

    (SELECT d.department, c.category, SUM(time_spent) as sum_quarantine 
    FROM master as m 
    INNER JOIN category as c ON c.cat_id = m.cat_id 
    INNER JOIN department as d ON d.dept_id = m.dept_id 
    WHERE category = 'Quarantine' GROUP BY d.department) as b 

    GROUP BY b.department 
+1

你能告訴我們你得到的輸出和你所期望的輸出嗎?可能還有一些輸入數據呢? –

回答

0

你想要可以不子查詢來完成,利用一個CASE WHEN的在SUM,所以什麼它只是概括你所感興趣的東西(「隔離」):

SELECT  d.department, 
      SUM(CASE c.category 
       WHEN 'Quarantine' THEN time_spent 
       END) as sum_quarantine, 
      SUM(time_spent) time_spent, 
      COUNT(DISTINCT (c.category)) category_count 
FROM  master as m 
INNER JOIN category as c ON c.cat_id = m.cat_id 
INNER JOIN department as d ON d.dept_id = m.dept_id 
GROUP BY d.department 
ORDER BY 1 

這裏是fiddle

請注意,我還添加了一個計數,因爲您的嘗試中有一個。但你的總是會返回1,所以我不知道你在找什麼。我已經添加了與部門相關的類別數量。

此外,您並未指定所需的訂單,但很容易修改ORDER BY條款。上面的查詢結果排序按部門,但舉例來說如果你想通過第二列按降序排序,然後做:

... 
ORDER BY 2 DESC 

如果結果包括NULL值,你希望有個零,而不是,然後使用COALESCE函數。例如:

COALESCE(SUM(time_spent), 0) time_spent, 
+0

這是可行的。謝謝一堆。現在唯一的問題是,如果一個部門沒有任何值,則查詢返回null。如何將null變爲0? – Brume007

+0

搜索「MySQL將null變爲0」會給出許多匹配。使用'COALESCE(....,0)',在那裏你可以將任何可能爲NULL的點設置爲0. – trincot

+0

非常感謝。它正在工作。你是個好人! – Brume007