| Start | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Simple Grouping Orders Table
When grouping by a specific column, only unique values of this column are returned. Return value:
Aggregate functions like Return value:
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| GROUP BY multiple columns One might want to GROUP BY more than one column will group by both age and name and will produce:
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| GROUP BY with ROLLUP and CUBE The ROLLUP operator is useful in generating reports that contain subtotals and totals. (7 row(s) affected) If the ROLLUP keyword in the query is changed to CUBE, the CUBE result set is the same, except these two additional rows are returned at the end: https://technet.microsoft.com/en-us/library/ms189305(v=sql.90).aspx (opens new window) |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Group by with multiple tables, multiple columns Group by is often used with join statement. Let's assume we have two tables. The first one is the table of students:
Second table is the table of subject each student can take:
And because one student can attend many subjects and one subject can be attended by many students (therefore N:N relationship) we need to have third "bounding" table. Let's call the table Students_subjects:
Now lets say we want to know the number of subjects each student is attending. Here the standalone The result of the given query is as follows:
For an even more complex example of GROUP BY usage, let's say student might be able to assign the same subject to his name more than once (as shown in table Students_Subjects). In this scenario we might be able to count number of times each subject was assigned to a student by GROUPing by more than one column: This query gives the following result:
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| HAVING Because the For example, using the following data: If we want to get the number of orders each person has placed, we would use and get
However, if we want to limit this to individuals who have placed more than two orders, we can add a will yield
Note that, much like our |
Read Article
https://develop.horje.com/learn/1434/reference