显示处理项目的所有用户并总结小时数

时间:2014-03-04 19:34:30

标签: mysql sum

我有一个看起来像这样的表:

+------+--------+---------+
| User | Actual | Project |
+------+--------+---------+
| A    | 5      | ProjA   |
| A    | 8      | ProjA   |
| B    | 3      | ProjA   |
| C    | 2      | ProjA   |
| B    | 8      | ProjB   |
| B    | 8      | ProjB   |
+------+--------+---------+

我的查询就像这样

 SELECT DISTINCT User, 
 SUM(Actual) AS Actual
 FROM Table
 Where Project = "ProjA" AND
 User = "A"

结果是

+------+--------+
| User | Actual |
+------+--------+
| A    | 13     |
+------+--------+

我想要实现的是查询显示所有处理该项目的用户,然后显示每个员工的实际总和,然后如果可能的话得到所有实际的总数,如下所示:

+------+--------+
| User | Actual |
+------+--------+
| A    | 13     |
| B    | 3      |
| C    | 2      |
+------+--------+

+-------+----+
| Total | 18 |
+-------+----+

我该怎么做?我尝试删除where子句中的User = "A",但这确实没有帮助。

1 个答案:

答案 0 :(得分:2)

SELECT user,
     SUM(actual) as actual
FROM `table`
Where Project = "ProjA"
GROUP BY user
WITH ROLLUP

WITH ROLLUP将为您提供一个用户值为NULL的总行。

sqlFiddle

如果你想要'Total'返回而不是NULL,你可以使用这个

SELECT if(User is NULL,'Total',User) as User,
     SUM(Actual) as Actual
FROM `table`
Where Project = "ProjA"
GROUP BY user
WITH ROLLUP

sqlFiddle

WITH ROLLUP非常甜蜜,因为它为您的所有GROUP BY提供摘要行,这样如果您想删除WHERE Project = "ProjA"并为每个项目和所有项目执行摘要,您可以执行以下操作

SELECT IF(Project IS NULL,'All Projects',Project) as Project,
       IF(User IS NULL,'Total',User) as User,
     SUM(Actual) as Actual
FROM `table`
GROUP BY Project,User
WITH ROLLUP

sqlFiddle

更新

如果您只想要ProjA的总数,那么

SELECT 'Total' as User,SUM(Actual) as Actual
FROM `table`
WHERE Project = "ProjA"

或者如果您只想从ROLLUP中选择总行,您可以这样做(不确定为什么要这样,但在这里)

SELECT User,Actual FROM
(SELECT if(User is NULL,'Total',User) as User,
     SUM(Actual) as Actual
FROM `table`
Where Project = 'ProjA'
GROUP BY User
WITH ROLLUP
 )T
WHERE User = 'Total'

sqlFiddle