Oracle group by functions

SQL

Oracle DB

If you want to follow along you can use this query for getting the same table as the exercise

1create table bricks (
2  brick_id integer,
3  colour   varchar2(10),
4  shape    varchar2(10),
5  weight   integer
6);
7
8insert into bricks values ( 1, 'blue', 'cube', 1 );
9insert into bricks values ( 2, 'blue', 'pyramid', 2 );
10insert into bricks values ( 3, 'red', 'cube', 1 );
11insert into bricks values ( 4, 'red', 'cube', 2 );
12insert into bricks values ( 5, 'red', 'pyramid', 3 );
13insert into bricks values ( 6, 'green', 'pyramid', 1 );
14
15commit;

Group by functions let us analyze information on a table with a single query, for example using the following table.

BRICK_IDCOLOURSHAPEWEIGHT
1bluecube1
2bluepyramid2
3redcube1
4redcube2
5redpyramid3
6greenpyramid1

We can group by colour and get the sum of the weight of all the figures of each colour

1SELECT colour, SUM(weight)
2FROM bricks
3GROUP BY colour;

The result is:

COLOURSUM(WEIGHT)
red6
green1
blue3

But then imagine that you want to group by but now by shape but also you want to see the group by colour so we can use GROUPING SETS()

1SELECT colour, shape, SUM(weight)
2FROM bricks
3GROUP BY GROUPING SETS(colour, shape);

So now with these query we obtain the following information.

COLOURSHAPESUM(WEIGHT)
-cube4
-pyramid6
green-1
blue-3
red-6