1. 程式人生 > >一道資料庫筆試題

一道資料庫筆試題

有一張表,記錄遊戲使用者id和它的等級,讓你計算 通關率=對每個等級,大於該等級的人數/大於等於該等級的人數。

解法:

首先統計每個等級人數到臨時表(用group by);

create table tmp select count(user_id) as cnt, grade from users group by grade;

然後計算每個等級的通關率(用臨時表自連線):
select tmp2.grade, tmp2.cnt/sum(tmp1.cnt) as gl from tmp as tmp1, tmp as tmp2 where tmp1.grade >= tmp2.grade group by tmp2.grade;