获得分组记录的总和

时间:2013-09-20 06:51:01

标签: php mysql group-by

首先,SQL Fiddle Demo

现在你可以在小提琴中看到我有两个名为projectworking的表,现在我已经将分组的项目组合在一起,除了第二个表有_QA后缀之外,它们具有相同的名称。

这意味着我已经成功实施了查询,允许我对该项目进行分组,但现在我还需要为这两个项目计算SUM计划时间。

如果你看到即将来临1000,但它必须是2500,这意味着projectproject_QA

的总和结果

感谢。

2 个答案:

答案 0 :(得分:3)

我的尝试......:

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 |

也许有人会提供更好的解决方案,但我还是无法提出更简单的查询...

答案 1 :(得分:0)

尝试其他解决方案 -

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