2012-10-03 51 views
4

我試圖完成顯示的計費對每個項目的總時數的查詢,在下面的格式:結合2個MySQL查詢到一個表具有獨特的行

Project Name | Hours 
Project A | 2 
Project B | 6 
Project C | 8 

我有兩個SQL的查詢計算每個項目計費的小時數。這是必要的,因爲每一個查詢有一個不同的JOIN:

例如,如果time_records.parent_type = '任務',則該連接是:

INNER JOIN time_records 
ON time_records.parent_id = project_objects.id 

如果time_records.parent_type = '項目',則加入是:

INNER JOIN time_records 
ON projects.id = time_records.parent_id 

我想這兩個查詢合併成一個表,但是我的問題是,表中重複,而不是將它們組合成一個唯一的行每個項目(類似於如何的項目,數據透視表將起作用)。

這裏是我當前的查詢:

(SELECT projects.name AS expr1 
    , sum(time_records.value) AS expr2 
FROM 
    project_objects 
INNER JOIN projects 
ON projects.id = project_objects.project_id 
INNER JOIN time_records 
ON time_records.parent_id = project_objects.id 
WHERE 
    time_records.parent_type = 'Task' 
GROUP BY 
    projects.name) 

UNION ALL 

(SELECT projects.name AS expr1 
     , sum(time_records.value) as expr2 
FROM 
    projects 
INNER JOIN time_records 
ON projects.id = time_records.parent_id 
WHERE 
    time_records.parent_type = 'Project' 
GROUP BY 
    projects.name) 

下面是它目前如何輸出:

Project Name | Hours 
Project A | 2 
Project B | 6 
Project C | 8 
Project A | 4 

我需要的項目A是在同一行,顯示出6小時的價值,而不是兩條線。我嘗試了UNION操作,但是這並沒有幫助。

回答

1

你可以試試這個,看看這是否正常工作?

SELECT X.expr1, SUM(X.expr2) 
FROM 
    (SELECT 
    projects.name AS expr1 
    , sum(time_records.value) AS expr2 
    FROM project_objects 
    INNER JOIN projects 
    ON projects.id = project_objects.project_id 
    INNER JOIN time_records 
    ON time_records.parent_id = project_objects.id 
    WHERE time_records.parent_type = 'Task' 
    GROUP BY projects.name 

    UNION 

    SELECT 
    projects.name AS expr1 
    , sum(time_records.value) as expr2 
    FROM projects 
    INNER JOIN time_records 
    ON projects.id = time_records.parent_id 
    WHERE time_records.parent_type = 'Project' 
    GROUP BY projects.name) X 
GROUP BY X.expr1 
+0

工作。謝謝! –

0

使用或使用條件連接

編輯:

檢查了這一點:最有可能的,這將在V工作。 Sum results from two select statements

SELECT projects.name AS nameval 
    , sum(time_records.value) AS total 
FROM ((SELECT projects.name AS expr1 
    , sum(time_records.value) AS expr2 
FROM 
    project_objects 
INNER JOIN projects 
ON projects.id = project_objects.project_id 
INNER JOIN time_records 
ON time_records.parent_id = project_objects.id 
WHERE 
    time_records.parent_type = 'Task' 
GROUP BY 
    projects.name) 

UNION ALL 

(SELECT projects.name AS expr1 
     , sum(time_records.value) as expr2 
FROM 
    projects 
INNER JOIN time_records 
ON projects.id = time_records.parent_id 
WHERE 
    time_records.parent_type = 'Project' 
GROUP BY 
    projects.name)) t group by expr1 
+0

OP提到根據上述條件,連接列是不同的。只用'OR'就足夠了。 – InSane

+0

so use_group by time_records.parent_type also – DevT

+0

問題是,如果parent_type ='Task',那麼它會在不同的表中查找項目,相比之下,如果parent_type ='Project' - 因此,只是一個簡單的OR不會區分JOIN的類型,對吧? –