本關任務:編寫函數來實現獲取前N名成績的方法。 提示:前面的實驗沒有提供編寫自定義函數的示例,需要參考OpenGauss數據庫文檔學習自定義函數的使用。
score
表內容如下:
Id Score 1 3.52 2 3.65 3 4.23 4 3.85 5 4.23 6 3.65
--#請在BEGIN - END之間添加實現代碼, 其余代碼不能改動
create TYPE ret as(rank bigint, SCORE float);
create or replace
function select_topN(topN INT)
RETURNS SETOF ret
AS $$
BEGIN
RETURN QUERY
WITH ranked_scores AS(SELECT score, DENSE_RANK() OVER(ORDER BY score DESC) as rank FROM score
)
SELECT rank, score
FROM ranked_scores
WHERE rank <= topN
ORDER BY rank, score DESC;END;
$$
language PLpgsql;
?