SQL141 试卷完成数同比2020年的增长率及排名变化
withtemp as (selectexam_id,tag,date(submit_time) as submit_timefromexamination_infoleft join exam_record using (exam_id)wheresubmit_time is not null),2021_temp as (selecttag,count(*) as exam_cnt_21,rank() over (order bycount(*) desc) as exam_cnt_rank_21fromtempwhereyear(submit_time) = 2021and (month(submit_time) between 1 and 6)group bytag),2020_temp as (selecttag,count(*) as exam_cnt_20,rank() over (order bycount(*) desc) as exam_cnt_rank_20fromtempwhereyear(submit_time) = 2020and (month(submit_time) between 1 and 6)group bytag)
selecttag,exam_cnt_20,exam_cnt_21,concat(round((exam_cnt_21 - exam_cnt_20) / exam_cnt_20 * 100,1),"%") as growth_rate,exam_cnt_rank_20,exam_cnt_rank_21,-- 修改为使用SIGNED转换,避免无符号整数减法问题CAST(exam_cnt_rank_21 AS SIGNED) - CAST(exam_cnt_rank_20 AS SIGNED) AS rank_delta
from2020_tempjoin 2021_temp using (tag)
order bygrowth_rate desc,exam_cnt_rank_21 desc
说明
因为在计算rank_delta
时,2021年的排名可能小于2020年的排名,导致无符号整数减法结果为负数,超出了BIGINT UNSIGNED的范围。
在MySQL中,当使用无符号整数(UNSIGNED)进行减法运算时,如果结果为负数,会报错"BIGINT UNSIGNED value is out of range"。