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_ID | COLOUR | SHAPE | WEIGHT |
---|---|---|---|
1 | blue | cube | 1 |
2 | blue | pyramid | 2 |
3 | red | cube | 1 |
4 | red | cube | 2 |
5 | red | pyramid | 3 |
6 | green | pyramid | 1 |
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:
COLOUR | SUM(WEIGHT) |
---|---|
red | 6 |
green | 1 |
blue | 3 |
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.
COLOUR | SHAPE | SUM(WEIGHT) |
---|---|---|
- | cube | 4 |
- | pyramid | 6 |
green | - | 1 |
blue | - | 3 |
red | - | 6 |