MySQL计算所有外部限制

时间:2011-07-14 08:36:06

标签: mysql

我有一个MySQL查询,它计算了我们在前五位客户中工作的小时数。这工作正常,我正在绘制图表上的数据。我想要实现的是在查询中的计算,该计算返回第六个结果集,该结果集是不在前五个中的所有小时的总和。即“其他”结果,以便所有6个结果的总和等于项目总和的总和。

我的查询:

SELECT
  SUM(projects.hours) AS total_hours
FROM projects
GROUP BY projects.companyID
ORDER BY total_hours DESC
LIMIT 5

3 个答案:

答案 0 :(得分:4)

SELECT
SUM(projects.hours) AS total_hours,
(SELECT SUM(projects.hours) FROM projects) AS all_hours
FROM 
projects
GROUP BY 
projects.companyID
ORDER BY total_hours DESC
LIMIT 5

从应用程序的all_hours中减去total_hours。

答案 1 :(得分:0)

SELECT
  1 no,
  projects.company,
  SUM(projects.hours) AS total_hours
FROM 
  projects
GROUP BY 
  projects.companyID
ORDER BY
  total_hours DESC
LIMIT 5

UNION ALL

SELECT
  2 no,
  'Others',
  SUM(projects.hours) AS total_hours
FROM 
  projects
WHERE projects.companyID NOT IN 
( SELECT companyID 
  FROM 
  (  SELECT
      projects.companyID
    FROM 
      projects
    GROUP BY 
      projects.companyID
    ORDER BY
      SUM(total_hours) DESC
    LIMIT 5
  ) AS tmp
)

答案 2 :(得分:0)

两种方法的组合如何,加上汇总我们可以消除IN的需要

(我不确定你是否rollup可以使用limit,我这里没有MYSQL因此无法测试,抱歉)

注意:我希望这会返回一个NULL的公司ID,其中包含其他行的总数

SELECT companyID, 
CASE WHEN companyID IS NULL THEN 
    sum(Total_hours)
ELSE
    sum(Total_hours) * -1
END

FROM 
(           
    SELECT companyID,SUM(projects.hours) AS total_hours,  
    FROM  projects 
    GROUP BY  projects.companyID 
    ORDER BY total_hours DESC WITH ROLLUP LIMIT 5 
    UNION ALL
    SELECT null,SUM(projects.hours)*-1 total_hours FROM projects  
)
GROUP BY companyID