1. 程式人生 > >修改後的SQL,可應用與RFM分析

修改後的SQL,可應用與RFM分析

 1.分組查詢,得到的是按科目分

SELECT  a.sname,a.sno,a.score,
 IF( @className = a.project_name,@rank := @rank + 1,@rank :=1 ) AS rank,
(@className := a.project_name) project_name
          FROM student23   a,
( select @rank :=0,@className := NULL ) b
ORDER BY a.project_name, a.score DESC ;

2.分組查詢,得到的是按學生人分

 SELECT  sname,
a.sno,a.score,
 IF( @sname = a.sname,@rank := @rank + 1,@rank :=1 ) AS rank,
  a.project_name,
(@sname := a.sname) sname
          FROM student23   a,
( select @rank :=0,@sname := NULL ) b
ORDER BY a.sname, a.score DESC ;

3.改進版

 SELECT  
a.sno,a.score,
 IF( @sname = a.sname,@rank := @rank + 1,@rank :=1 ) AS rank,
  a.project_name,
(@sname := a.sname) sname
          FROM student23   a,
( select @rank :=0,@sname := NULL ) b
ORDER BY a.sname, a.score DESC ;

綜上所述,mysql實現Oracle中的partition by 的效果已基本完成。如果要顯示前幾條,可用where rank <=條數