In SQL group by problem

In use the sql statement, we often use the group by adding a polymerization function group and polymerized, to achieve certain requirements. However, incorrect use group by and aggregate functions, will bring a very vague question.

There is such a demand: The tables are grouped to find out first-time users get all the information that record the highest score.

To this end, I created a table record checkpoints user information recorded score information obtained under different user levels in different areas of the course:

pass_log table

At first I felt very simple, sql is written like this:

select pl.id, pl.user_id, pl.course_id, pl.pass_id, max(pl.total_score)
from pass_log pl
group by pl.user_id, pl.course_id, pl.pass_id;

The result is this:

 They found no clues? Grouping and aggregation of the results are right, but id is wrong, the correct id should be respectively 3,5 ah! But why take that 1,4 it? Because it was taken after the first record id packet! That should change how come it? My idea is to get the highest score after the information and the grouping, and then the original table in the association:

select p.id, p.user_id, p.course_id, p.pass_id, p.total_score
from pass_log p
join (
    select pl.user_id, pl.course_id, pl.pass_id, max(pl.total_score) maxTotalScore
    from pass_log pl
    group by pl.user_id, pl.course_id, pl.pass_id) t
on p.user_id = t.user_id and p.course_id = t.course_id and p.pass_id = t.pass_id
where p.total_score = maxTotalScore
group by p.user_id, p.course_id, p.pass_id;

The reason I added the group by the outermost layer is the user may get the highest score several times in the same hurdle, but I just want to get that record the highest score for the first time, the final result is correct, as shown:

Then I want to check out the data is wrong, why it is not being given mysql? This is not pit me? Later found really will be incorrect report, the Executive sql observed:

select @@global.sql_mode;

If the result contains ONLY_FULL_GROUP_BY then execute my first sql statement will error, error if you do not want to make pl.id changed any_value (pl.id), but the result was taken after the first packet id It is not the result I wanted.

In fact, I finally want to express is that if your group by statement is no problem in an environment, but in other circumstances they reported abnormal, it will be your group by using the wrong?

Guess you like

Origin www.cnblogs.com/liuzhulin/p/12229976.html