首先这里是SQL Fiddle Demo。
现在你可以在小提琴中看到我有两个名为的表project
,working
现在我已经将项目分组在一起,除了第二个表有_QA
后缀之外,它们具有相同的名称。
这意味着我已经成功实现了允许我对该项目进行分组的查询,但现在我还需要对这两个项目的计划时间进行求和。
如果您在小提琴中看到它的到来,1000
但它必须2500
意味着两者的总和project
结果project_QA
谢谢。
首先这里是SQL Fiddle Demo。
现在你可以在小提琴中看到我有两个名为的表project
,working
现在我已经将项目分组在一起,除了第二个表有_QA
后缀之外,它们具有相同的名称。
这意味着我已经成功实现了允许我对该项目进行分组的查询,但现在我还需要对这两个项目的计划时间进行求和。
如果您在小提琴中看到它的到来,1000
但它必须2500
意味着两者的总和project
结果project_QA
谢谢。
我的尝试....:
SELECT p.name,
(SELECT SUM(p1.planned_hour)
FROM project p1
WHERE REPLACE(p1.name,'_QA','') = REPLACE(p.name,'_QA','') ) AS ProjectPlannedHour,
SUM( ROUND( TIME_TO_SEC( TIMEDIFF( vv.end_date, vv.start_date ) ) / 3600 ,2)) AS TotalHour
FROM project p
INNER JOIN working vv ON vv.project_id = p.id
GROUP BY REPLACE(p.name,'_QA','')
ORDER BY TotalHour DESC
LIMIT 0,5
加入:
SELECT p.name,
p1.planned_hour AS ProjectPlannedHour,
SUM(ROUND(TIME_TO_SEC(TIMEDIFF(vv.end_date, vv.start_date)) / 3600 ,2)) AS TotalHour
FROM project p
INNER JOIN working vv ON vv.project_id = p.id
INNER JOIN (SELECT REPLACE(name,'_QA','') AS `name`,
SUM(planned_hour) AS planned_hour
FROM project
GROUP BY REPLACE(name,'_QA','')) p1
ON REPLACE(p1.name,'_QA','') = REPLACE(p.name,'_QA','')
GROUP BY REPLACE(p.name,'_QA','')
ORDER BY TotalHour DESC LIMIT 0, 5
结果:
| NAME | PROJECTPLANNEDHOUR | TOTALHOUR |
|---------|--------------------|-----------|
| project | 2500 | 4.67 |
也许有人给出了更好的解决方案,我还不能弄清楚更简单的查询......
尝试另一种解决方案 -
SELECT GROUP_CONCAT(NAME) name, SUM(planned_hour) planned_hour, SUM(TotalHour) TotalHour FROM (
SELECT
p.name,
p.planned_hour,
SUM(TIMESTAMPDIFF(SECOND, vv.start_date, vv.end_date)) / 3600 TotalHour
FROM
project p
INNER JOIN
working vv ON vv.project_id = p.id
GROUP BY
p.id) t;
它有点简化。结果是:
project,project_QA 2500 4,6667