4

我正在尝试完成一个查询,显示每个项目计费的总小时数,格式如下:

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

我有两个 SQL 查询来计算每个项目计费的小时数。这是必要的,因为每个查询都有不同的 JOIN:

例如,如果 time_records.parent_type = 'Task',那么 Join 是:

INNER JOIN time_records
ON time_records.parent_id = project_objects.id

如果 time_records.parent_type = 'Project',那么 Join 是:

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 操作,但这没有帮助。

4

2 回答 2

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
于 2012-10-03T04:12:59.873 回答
0

使用 OR 条件连接

编辑:

检查一下:这很可能对你有用。 对两个 select 语句的结果求和

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
于 2012-10-03T03:45:22.397 回答