Solved

MySQL query to get group total using Group by With ROLLUP?

Posted on 2013-01-04
1
2,650 Views
Last Modified: 2013-01-05
Please help me with MySQL query, thanks.

Here is my sample table:

ID  Service Quantity
3          a             3
1          a             2
12        c           22
5          c           6
10        c            3
20        b            1
11        b            1
4          b            2


I would like to get the subtotal and total, the data is grouped by and sorted by service, also in each group, ID is sorted,  the result is as belowt:
ID Service Quantity
1        a         2
3        a         3
Subtotal :    5
            
4       b         2
11     b         1
20     b         1
Subtotal:    4
            
5       c        6
10     c        3
12     c      22
Subtotal:   31  

Total:         40
0
Comment
Question by:HemlockPrinters
1 Comment
 
LVL 26

Accepted Solution

by:
Chris Luttrell earned 500 total points
ID: 38746372
This is a way to do it in SQL Server :
CREATE TABLE sample (ID INT,  Service CHAR(1), Quantity INT);
INSERT INTO SAMPLE VALUES 
(3, 'a', 3),
(1, 'a', 2),
(12, 'c', 22),
(5, 'c', 6),
(10, 'c', 3),
(20, 'b', 1),
(11, 'b', 1),
(4, 'b', 2);

SELECT	ID, 
	CASE WHEN Service IS NULL THEN 'Total:'  
		WHEN ID IS NULL THEN 'Subtotal:' 
		ELSE Service END Service, 
	SUM(Quantity) Quantity
FROM sample
GROUP BY Service, ID
WITH ROLLUP

DROP TABLE sample

Open in new window

which yields these results:Rollup Results(sampe written and run on SQL 2008 so INSERT will need tweaked for SQL 2005, but the SELECT ... WITH ROLLUP will work in 2005)
0

Featured Post

Optimizing Cloud Backup for Low Bandwidth

With cloud storage prices going down a growing number of SMBs start to use it for backup storage. Unfortunately, business data volume rarely fits the average Internet speed. This article provides an overview of main Internet speed challenges and reveals backup best practices.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

As a database administrator, you may need to audit your table(s) to determine whether the data types are optimal for your real-world data needs.  This Article is intended to be a resource for such a task. Preface The other day, I was involved …
In this article we will get to know that how can we recover deleted data if it happens accidently. We really can recover deleted rows if we know the time when data is deleted by using the transaction log.
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…

756 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question