我試圖完成顯示的計費對每個項目的總時數的查詢,在下面的格式:結合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操作,但是這並沒有幫助。
工作。謝謝! –