SQL function calculation and union

  • truncated mean

    SELECT
    	b.tag,
    	b.difficulty,
    	-- 去掉最大值与最小值取平均,保留一位小数
    	ROUND(( SUM( a.score )- MAX( a.score )- MIN( a.score ))/( COUNT( score )- 2 ), 1 ) 
    FROM
    	examination_info b
    	LEFT JOIN exam_record a ON b.exam_id = a.exam_id 
    WHERE
    	b.tag = "SQL" 
    	AND b.difficulty = "hard"
    
  • Minimum value greater than average query
    Subquery divides values ​​greater than average. Then find the minimum value that meets the conditions. Remember: Be sure to connect to the query again. Otherwise, all values ​​greater than the SQL mean are queried instead of only the SQL values ​​greater than the SQL mean.

    SELECT
    	MIN( score ) 
    FROM
    	exam_record er
    	JOIN examination_info ei ON er.exam_id = ei.exam_id 
    WHERE
    	ei.tag = 'SQL' 
    	AND score >= (
    	SELECT
    		AVG( score ) 
    	FROM
    		examination_info a
    		LEFT JOIN exam_record b ON a.exam_id = b.exam_id 
    	WHERE
    	a.tag = "SQL" 
    	)
    
  • Calculate the number of days in the month

    SELECT
    	LAST_DAY(submit_time),  -- 月度最后一天
    	DATE(DATE_ADD( submit_time, INTERVAL - DAY ( submit_time )+ 1 DAY )), -- 月度第一天
    	DATEDIFF(LAST_DAY(submit_time),DATE(DATE_ADD( submit_time, INTERVAL - DAY ( submit_time ) DAY ))),  -- 该月一共有几天(法1)
    	DAY(LAST_DAY(submit_time))  -- 该月一共有几天(法2)
    from  practice_record
    
  • UNION

    • When using the keyword union, the multiple query results to be unioned cannot be ordered by themselves first, but they must be united first, and then order by according to a certain field.
    • The SELECT statements inside the UNION must have the same number of columns. Columns must also have similar data types. Also, the order of the columns in each SELECT statement must be the same.
    SELECT
    	DATE_FORMAT( submit_time, '%Y%m' ) as submit_month ,
    	COUNT( question_id ) `month_q_cnt`,
    	ROUND( COUNT( question_id )/ DAY ( LAST_DAY( max( submit_time ) )), 3 ) `avg_day_q_cnt` 
    FROM
    	practice_record 
    WHERE
    	YEAR ( submit_time )= '2021' 
    	AND score IS NOT NULL 
    GROUP BY
    	DATE_FORMAT( submit_time, '%Y%m' ) 
    UNION all
    SELECT
    	CONCAT( YEAR ( MIN( submit_time )), '汇总' ) `submit_month `,
    	COUNT( 1 ) `month_q_cnt`,
    	ROUND( COUNT( question_id )/ 31, 3 ) `avg_day_q_cnt` 
    FROM
    	practice_record 
    WHERE
    	YEAR ( submit_time )= '2021' 
    	AND score IS NOT NULL
    ORDER BY submit_month   -- 只能在最后排序
    
  • The moving average needs to use the window function, for details, please refer to the details of the window function

Guess you like

Origin blog.csdn.net/weixin_44964850/article/details/123349119