The GROUP BY statement is used to grouping the rows that have the same values in the table.
Grouping lets you divide data into logical sets so that you can perform aggregate calculations on each group. Groups are created using the GROUP BY clause in the SELECT statement.
The GROUP BY clause instructs the DB2 to group the data and then perform the aggregate on each group rather than on the entire result set.
SELECT column_name(s) FROM table_name WHERE condition GROUP BY column_name(s); |
Below is a selection from the "Product" table in the DB2 database.
ProductID | ProductName | Category | Price | QtyOnHand | TotalValue |
---|---|---|---|---|---|
7001 | Mouse | Accessories | 75.00 | ||
7002 | Harddrive | Accessories | 65.00 | 20 | 1,300 |
7003 | Keyboard | Accessories | 36.00 | 33 | 1,118.00 |
7004 | Ram | Components | 23.50 | 16 | 376.00 |
7005 | Honda | Bikes | 1,200 | ||
7006 | Pen | Stationery | 7.45 | 10 | 74.50 |
7007 | Pendrive | Accessories | 65.00 | 20 | 1,300 |
The following SQL statement lists the number of different Category in "Product" table.
SELECT Category, COUNT(Category) As "Number_of_Products" FROM Product GROUP BY Category; |
The GROUP BY clause instructs DB2 to sort the data and group it by Category. This causes "Number_of_Products" to be calculated once per Category rather than once for the entire table.
The result of this query is as follows.
Category | Number_of_Products |
---|---|
Accessories | 4 |
Components | 1 |
Bikes | 1 |
Stationery | 1 |
If you have any doubts or queries related to this chapter, get them clarified from our Mainframe experts on ibmmainframer Community!