SQL calculation function and group query

Continue to read Niu Ke questions and record some knowledge points

1. Check the highest and lowest result keywords order by and limit max

 

select gpa form user_profile where university='复旦大学' order by gpa desc limit 1
select max(gpa) as gap from user_profile where university ='复旦大学'

2. Statistics keyword count rounded count

 round is rounding, and 1 in round means to keep one decimal place. Since men are required, where uses gender=male to restrict. Then count is used to count.

select
    count(gender) as male_num,
    round(avg(gpa), 1) as avg_gpa
from
    user_profile
where
    gender = 'male'

3. Group calculation keyword group by 

 Topic analysis: Calculate each school and each gender: use group by, calculate the number of users count, the average active days avg function within 30 days, and the average number of posts avg

select
    gender,
    university,
    count(device_id) as user_num,
    avg(active_days_within_30) as avg_active_day,
    avg(question_cnt) as avg_question_cnt
from
    user_profile
group by
    gender,
    university

It involves the correct sorting order: from (to assemble data from different data sources), to where (to filter and sort the data based on specified conditions) and then to use group by (to divide the filtered data into multiple groups), having, and finally select.

First determine which table the data comes from, and then filter the data according to the where condition, and then perform group by grouping (there can be multiple grouping conditions, grouping in order of fields), after grouping, the results are filtered by having to present the data .

4. Group filtering keywords group by and having

select
    university,
    avg(question_cnt) as avg_question_cnt,
    avg(answer_cnt) as avg_answer_cnt
from
    user_profile
group by
    university
having
    avg_question_cnt < 5
    or avg_answer_cnt< 20

Why not use where to do conditional filtering, because the result of the aggregation function is used as the filtering condition, you cannot use where, but use the having syntax and rename it. having is usually used with the group by function.

5. Grouping and sorting keywords group by and order by

select
    university,
    avg(question_cnt) as avg_question_cnt
from
    user_profile
group by
    university
order by
    avg_question_cnt ASC

First select from user_profile, then execute group by university, then execute select, and finally execute order by and then sort.

Guess you like

Origin blog.csdn.net/weixiwo/article/details/130025322