开发者

MySQL two different groupings required in one query

Struggling to do this with one query:

scores
==========

| child_name | week | behaviour_score | test | test_score |
+---------------------------------------------------------+
| jo         | 1    | 75              | 1    | 55         |
| jo         | 1    | 75              | 2    | 54         |
| jo         | 2    | 71              | 1    | 65         |
| jo         | 3    | 68              | 1    | 70         |
| jo         | 3    | 68              | 2    | 74         |
| jo         | 3    | 68              | 3    | 45         |

Each child takes 1 to n tests each week. Behaviour is recorded as a value for the week, but is stored in each row - so e.g. jo's behaviour for week 1 is 75, and for week 3 is 68. It's not normalised. I know. Wasn't my call.

The table contains records like this for many children.

I am trying to return 1 row per child, with name, sum of behaviour, and sum of test scores. But because behaviour isnt normalised it must only count the value once per week.

So sum of behaviour above is 75+71+68 And sum of test scores is 55+54+65+70+74+45

My first attempt was

SELECT 
    child_name, 
    SUM(behaviour_score), 
    SUM(test_Score) 
FROM results 
GROUP BY child_name

But of course,开发者_如何学C that gives too large a value for behaviour score as it doesnt account for the values being duplicated for a given week.

Is it possible to achieve this with one query?


You need to first reduce the data into one row per child, per week with the total test score but only one (let's take the MAX) behavior score), then base your query on that:

SELECT 
   child_name, 
   SUM(behaviour_score), 
   SUM(test_Score) 
FROM (
      SELECT child_name, MAX(behavior_score), SUM(test_Score)
      FROM result GROUP BY child_name, week
     ) AS OnePerWeek
GROUP BY child_name
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜