Question

I have a table that looks like this:

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

My query is like this

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

The result is

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

What I would like to achieve is for the query to show all the Users that worked on that project and then the sum of the Actual per employee and then if possible get the total of all the Actual, something like this:

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

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

How should I do this? I tried removing the User = "A" in the where clause but that really didn't help.

Was it helpful?

Solution

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

WITH ROLLUP will give you a total row with user value of NULL.

sqlFiddle

if you want 'Total' returned instead of NULL you can use this

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 is pretty sweet in that it provides summary lines for all your GROUP BY so that if you wanted to drop the WHERE Project = "ProjA" and do summaries for each project and all projects you can do something like below.

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

updated

If you just want the total of ProjA you can do

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

or if you want to just select the total row from the ROLLUP you can do this (not sure why you want to but here it is)

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top