SERPland Oracle, PL/SQL, PHP, Autos, Bungalow-Hotels and more …

23Nov/060

Oracle SQL: Summarize a calculated column (like a count(*) column) with ROLLUP


You have a simple sql statement like this:

select machine, count(*) as users
from v$session
group by machine

This query returns the session count on each machine:

MACHINE USERS
machine1 16
machine2 17
machine3 15
machine4 14

Now you'd like to know the total number of users. You could manually summarize 16, 17, 15 and 14 to the total of 62.
Or you could execute another query without grouping the "machine".
The best way would be an automated summary of the number of users in our actual query.
It's simple!

Just use the ROLLUP analytical function:

select machine, count(*) as users
from v$session
group by rollup (machine)

This ease use of the rollup analytical functions summarizes our users count.
Now, an additional row in the query result set return the total users count of 62.

MACHINE USERS
machine1 16
machine2 17
machine3 15
machine4 14
"total" . . . 62

Reference:

SELECT [column,] group function(column) . ,
GROUPING(expr)
FROM table
[WHERE condition]
[GROUP BY [ROLLUP][CUBE] group by expression]
[HAVING having expression ]
[ORDER BY column];

When using mySql instead of Oracle, just use the "WITH ROLLUP" clause.

Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


No trackbacks yet.

You might also like

Oracle Reports Query not linkable: REP-20147 error (group link) In Oracle Report you can not link query blocks on items when you see this No-Link Item: Cannot implement...
CASE expression in Oracle SQL statement Let's think we write a select statement and would like to DECODE (on Oracle database) on a column: DECODE(bew.bewart_tid,...
Error / Problem: select statement returns no rows – but result set contains about 3 rows (from CW_ALL_DB_LINKS / sys.link$ / Oracle9i) CAST Application Mining Error/Problem: Following select statement returns no rows - but result set...
SQL Trace with Oracle Database Enable SQL Trace for my own single session: ALTER SESSION SET SQL_TRACE = TRUE; Or use a pl/sql...
Grab This Widget