16
14
**SQL HAVING Example**
18
16
Take a look at the "Activities" table:
20
+---------+--------------+--------------+-------------+----------+
21
|Id |ActivityDate |ActivityType |ActivityCost | userID |
22
+=========+==============+==============+=============+==========+
23
| 1 |2011-01-02 | Sport |45 |131 |
24
+---------+--------------+--------------+-------------+----------+
25
| 2 |2011-01-02 | Art |10 |256 |
26
+---------+--------------+--------------+-------------+----------+
27
| 3 |2011-01-02 | Music |25 |022 |
28
+---------+--------------+--------------+-------------+----------+
29
| 4 |2011-01-02 | Food |125 |022 |
30
+---------+--------------+--------------+-------------+----------+
31
| 5 |2011-01-03 | Music |40 |131 |
32
+---------+--------------+--------------+-------------+----------+
33
| 6 |2011-01-03 | Food |20 |175 |
34
+---------+--------------+--------------+-------------+----------+
36
In order to find if any users have spent more than $100 on recreational activities, use the following SQL statement:
18
+---------+--------------+--------------+-------------+----------+
19
|Id |ActivityDate |ActivityType |ActivityCost | userID |
20
+=========+==============+==============+=============+==========+
21
| 1 |2011-01-02 | Sport |45 |131 |
22
+---------+--------------+--------------+-------------+----------+
23
| 2 |2011-01-02 | Art |10 |256 |
24
+---------+--------------+--------------+-------------+----------+
25
| 3 |2011-01-02 | Music |25 |022 |
26
+---------+--------------+--------------+-------------+----------+
27
| 4 |2011-01-02 | Food |125 |022 |
28
+---------+--------------+--------------+-------------+----------+
29
| 5 |2011-01-03 | Music |40 |131 |
30
+---------+--------------+--------------+-------------+----------+
31
| 6 |2011-01-03 | Food |20 |175 |
32
+---------+--------------+--------------+-------------+----------+
34
In order to find if any users have spent more than $100 on recreational activities, use the following SQL statement: ::
40
36
SELECT userID,SUM(ActivityCost) FROM Activities
44
40
The result-set will look like this:
46
====== ===============
47
userID SUM(OrderPrice)
48
====== ===============
42
====== ===============
43
userID SUM(OrderPrice)
44
====== ===============
50
46
====== ===============
52
48
Now we want to find if userIDs "131", "256", or "175" spent less than $50 on Activities.
54
We add an ordinary WHERE clause to the SQL statement:
50
We add an ordinary WHERE clause to the SQL statement: ::
58
52
SELECT userID,SUM(ActivityCost) FROM Activities
59
53
WHERE userID='131' OR userID='256' OR userID="175"