I have an SQL query that get the number of jobs, gross weight etc for different companies.
The result in MySQL Workbench looks like this:
I would like to add another row at the bottom that calculates the total of each column i.e the total of the jobs column would be 267. How do I add an extra row for the totals?
SQL query:
select c.Name, COUNT(distinct jn.ID) as Jobs, SUM(jn.ActualWeight) as GrossWt, SUM(jpc.AdvisedQty) AS Units_In, SUM(jpd.AdvisedQty) AS Units_Out FROM customer c LEFT JOIN job_new jn ON jn.JobOwnerID = c.ID LEFT JOIN job_pieces jp ON jp.JobID = jn.ID LEFT JOIN job_pieces jpc ON jpc.JobID = jn.ID AND jn.CollectMemberID = jn.JobOwnerID LEFT JOIN job_pieces jpd ON jpd.JobID = jn.ID AND jn.DeliverMemberID = jn.JobOwnerID WHERE jn.IsActive = 1 GROUP BY jn.JobOwnerID
Advertisement
Answer
You are looking for the GROUP BY
modifier WITH ROLLUP
:
select c.Name, COUNT(distinct jn.ID) as Jobs, SUM(jn.ActualWeight) as GrossWt, SUM(jpc.AdvisedQty) AS Units_In, SUM(jpd.AdvisedQty) AS Units_Out FROM customer c LEFT JOIN job_new jn ON jn.JobOwnerID = c.ID LEFT JOIN job_pieces jp ON jp.JobID = jn.ID LEFT JOIN job_pieces jpc ON jpc.JobID = jn.ID AND jn.CollectMemberID = jn.JobOwnerID LEFT JOIN job_pieces jpd ON jpd.JobID = jn.ID AND jn.DeliverMemberID = jn.JobOwnerID WHERE jn.IsActive = 1 GROUP BY c.Name WITH ROLLUP;
Note: I also changed the GROUP BY
key for two reasons. First, it really should match the column used in the SELECT
. Second, you were using a value from a LEFT JOIN
ed table, so the value could be NULL
. That is usually undesirable.