group-by-having-clauses.txt 1.18 KB
Newer Older
1
* GROUP BY and HAVING clauses can be used for dealing with aggregate functions
phuson's avatar
phuson committed
2
* Following aggregate functions are available on DQL: COUNT, MAX, MIN, AVG, SUM
3 4 5

Selecting alphabetically first user by name.

jackbravo's avatar
jackbravo committed
6
<code type="sql">
7 8 9 10 11
SELECT MIN(u.name) FROM User u
</code>

Selecting the sum of all Account amounts.

jackbravo's avatar
jackbravo committed
12
<code type="sql">
13 14 15 16 17
SELECT SUM(a.amount) FROM Account a
</code>

* Using an aggregate function in a statement containing no GROUP BY clause, results in grouping on all rows. In the example above we fetch all users and the number of phonenumbers they have.

jackbravo's avatar
jackbravo committed
18
<code type="sql">
19 20 21 22 23
SELECT u.*, COUNT(p.id) FROM User u, u.Phonenumber p GROUP BY u.id
</code>

* The HAVING clause can be used for narrowing the results using aggregate values. In the following example we fetch all users which have atleast 2 phonenumbers

jackbravo's avatar
jackbravo committed
24
<code type="sql">
25 26 27 28 29 30 31 32 33 34 35 36
SELECT u.* FROM User u, u.Phonenumber p HAVING COUNT(p.id) >= 2
</code>

<code type="php">
// retrieve all users and the phonenumber count for each user

$users = $conn->query("SELECT u.*, COUNT(p.id) count FROM User u, u.Phonenumber p GROUP BY u.id");

foreach($users as $user) {
    print $user->name . ' has ' . $user->Phonenumber[0]->count . ' phonenumbers';
}
</code>