Solved

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

Posted on 2013-01-04
1
2,675 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

by Mark Wills Attending one of Rob Farley's seminars the other day, I heard the phrase "The Accidental DBA" and fell in love with it. It got me thinking about the plight of the newcomer to SQL Server...  So if you are the accidental DBA, or, simp…
Creating and Managing Databases with phpMyAdmin in cPanel.
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…

738 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