Oracle 5.0 Reference Manual page 993

Table of Contents

Advertisement

(
year
INT NOT NULL,
country VARCHAR(20) NOT NULL,
product VARCHAR(32) NOT NULL,
profit
INT
);
The table's contents can be summarized per year with a simple
mysql>
SELECT year, SUM(profit) FROM sales GROUP BY year;
+------+-------------+
| year | SUM(profit) |
+------+-------------+
| 2000 |
4525 |
| 2001 |
3010 |
+------+-------------+
This output shows the total profit for each year, but if you also want to determine the total profit
summed over all years, you must add up the individual values yourself or run an additional query.
Or you can use ROLLUP, which provides both levels of analysis with a single query. Adding a
modifier to the
ROLLUP
grand total over all year values:
mysql>
SELECT year, SUM(profit) FROM sales GROUP BY year WITH ROLLUP;
+------+-------------+
| year | SUM(profit) |
+------+-------------+
| 2000 |
4525 |
| 2001 |
3010 |
| NULL |
7535 |
+------+-------------+
The grand total super-aggregate line is identified by the value
has a more complex effect when there are multiple
ROLLUP
time there is a "break" (change in value) in any but the last grouping column, the query produces an
extra super-aggregate summary row.
For example, without ROLLUP, a summary on the
might look like this:
product
mysql>
SELECT year, country, product, SUM(profit)
->
FROM sales
->
GROUP BY year, country, product;
+------+---------+------------+-------------+
| year | country | product
+------+---------+------------+-------------+
| 2000 | Finland | Computer
| 2000 | Finland | Phone
| 2000 | India
| Calculator |
| 2000 | India
| Computer
| 2000 | USA
| Calculator |
| 2000 | USA
| Computer
| 2001 | Finland | Phone
| 2001 | USA
| Calculator |
| 2001 | USA
| Computer
| 2001 | USA
| TV
+------+---------+------------+-------------+
The output indicates summary values only at the year/country/product level of analysis. When
is added, the query produces several extra rows:
mysql>
SELECT year, country, product, SUM(profit)
->
FROM sales
->
GROUP BY year, country, product WITH ROLLUP;
+------+---------+------------+-------------+
| year | country | product
+------+---------+------------+-------------+
GROUP BY
clause causes the query to produce another row that shows the
GROUP BY
| SUM(profit) |
|
1500 |
|
100 |
150 |
|
1200 |
75 |
|
1500 |
|
10 |
50 |
|
2700 |
|
250 |
| SUM(profit) |
973
Modifiers
GROUP BY
in the
NULL
GROUP BY
table based on year, country, and
sales
like this:
WITH
column.
year
columns. In this case, each
ROLLUP

Advertisement

Table of Contents
loading

This manual is also suitable for:

Mysql 5.0

Table of Contents