jump to navigation

mysql with rollup for a easy grouped total columns in result set June 4, 2009

Posted by chris in : SQL , trackback

Using the WITH ROLLUP modifier in queries using GROUP BY will add an additional row to the result set which sums all columns. This prevents you from having you to write code which adds each column in your programming language.

Description from the Mysql Reference Manual

The GROUP BY clause allows a WITH ROLLUP modifier that causes extra rows to be added to the summary output. These rows represent higher-level (or super-aggregate) summary operations. ROLLUP thus allows you to answer questions at multiple levels of analysis with a single query. It can be used, for example, to provide support for OLAP (Online Analytical Processing) operations.

Example

SELECT
	DATE(dateTime) AS order_date, count(*) as shipments, sum(shipping_total) as shipping_total, sum(hasShipAmt) as hasShipAmt, sum(shipping_total)-sum(hasShipAmt) AS revenue
FROM
	tbl_my_orders
WHERE
	dateTime BETWEEN '$startDate' AND '$endDate 23:59:59'
GROUP BY
	order_date WITH ROLLUP

Comments»

no comments yet - be the first?