Custom window function in Mysql, row_number, dense_rank.

In data warehouse development or data analysis, we often use windowing functions.

But what should we do without us in Mysql?

The following are two examples encountered in actual development, share with you, I hope to help you

Custom implementation row_number

SELECT student_id, student_name
	, @i := @i + 1 AS rownum
FROM student, (
		SELECT @i := 0
	) t

Through the above sql, we can see that it is actually very simple. Just define the variable i , and then increment i by +1  after each column  .

 

Customize dense_rank

SELECT student_id, student_name,student_answer, 
	 CASE 
		WHEN @prevRank = student_answer THEN @curRank
		ELSE @curRank := @curRank + 1
	END AS rankNO, @prevRank := student_answer
FROM lesson_student_fact_real, (
		SELECT @curRank := 0, @prevRank := NULL
	) r

Customizing dense_rank is also very simple, but dense_rank needs to be determined based on a data column to determine whether it is equal, so two variables must be defined to achieve it. If the value is equal, the value will not change , otherwise it will be +1

Guess you like

Origin blog.csdn.net/zhangyupeng0528/article/details/112983454