My question is related to the semantic of SQL's GROUP BY
primitive.
Suppose that we have the following relation (Users):
+----+------+---------------+-----+
| id | name | country | age |
+----+------+---------------+-----+
| 1 | Foo | Brazil | 20 |
| 2 | Bar | Japan | 20 |
| 3 | Baz | Brazil | 22 |
| 4 | Quz | Brazil | 18 |
+----+------+---------------+-----+
I expected that the following dummy query:
SELECT name, country, avg(age)
FROM Users
GROUP BY country
returns four tuples, since we used a non-grouped attribute in the SELECT
projection:
+------+---------------+-----+
| name | country | age |
+------+---------------+-----+
| Foo | Brazil | 20 |
| Bar | Japan | 20 |
| Baz | Brazil | 20 |
| Quz | Brazil | 20 |
+------+---------------+-----+
Yet, it yields the following tuples:
+------+---------------+-----+
| name | country | age |
+------+---------------+-----+
| Foo | Brazil | 20 |
| Bar | Japan | 20 |
+------+---------------+-----+
Why?
Edit: found out that Why can't you mix Aggregate values and Non-Aggregate values in a single SELECT? answers this question.