Jump to content

Group by question with example


shebbycs

Recommended Posts

There are 3 questions which are :

 

1. Group functions work across many rows to produce one result per group (My answer : Yes)

 

2. Group functions include Null in calculations (My answer : Yes and No)

 

3. There WHERE clause restricts rows prior to inclusion in a group calculations. (My answer : Yes)

 

But each of these questions need to give a example for every statement

 

Hope you can help me please 

 

Thank you :)

Link to comment
Share on other sites

The data

+--------+-------+-----------+-------+
| idtest | name  | subject   | score |
+--------+-------+-----------+-------+
|      1 | Peter | English   |  NULL |
|      2 | Peter | Maths     |    84 |
|      3 | Peter | Chemistry |    66 |
|      4 | Mary  | English   |    90 |
|      5 | Mary  | Maths     |    80 |
|      6 | Mary  | Chemistry |    50 |
|      7 | Paul  | English   |    60 |
|      8 | Paul  | Maths     |     0 |
|      9 | Paul  | Chemistry |   100 |
+--------+-------+-----------+-------+


1. Find the total score for each student

mysql> SELECT name, SUM(score) as total
    -> FROM testdata
    -> GROUP BY name;
+-------+-------+
| name  | total |
+-------+-------+
| Mary  |   220 |
| Paul  |   160 |
| Peter |   150 |
+-------+-------+


2. Find the average score for each subject

mysql> SELECT subject, SUM(score) as total, COUNT(*) as num,
    -> COUNT(score) as numscores, AVG(score) as average
    -> FROM testdata
    -> GROUP BY subject;
+-----------+-------+-----+-----------+---------+
| subject   | total | num | numscores | average |
+-----------+-------+-----+-----------+---------+
| Chemistry |   216 |   3 |         3 | 72.0000 |
| English   |   150 |   3 |         2 | 75.0000 |  <-- null was ignored
| Maths     |   164 |   3 |         3 | 54.6667 |
+-----------+-------+-----+-----------+---------+

Note there was a NULL score for English which was ignored, (so the answer is NO they are not included in group aggregations)

 

3. Find the lowest non-zero score

mysql> SELECT MIN(score) as lowest
    -> FROM testdata
    -> WHERE score > 0;
+--------+
| lowest |
+--------+
|     50 |
+--------+
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.