mysql中使用分析函数(开窗函数)

众说周知,oracle的分析函数用于复杂的统计方面非常好用,但mysql不支持oracle的分析函数(开窗函数),怎么办呢?

我们可以通过另外的途径来使用,直接贴上代码:

create table income_tl(
	user_id int,
	create_date date,
	income int
);

insert into income_tl values(1,'2016-03-01',100);
insert into income_tl values(1,'2016-03-02',300);
insert into income_tl values(1,'2016-03-03',200);
insert into income_tl values(1,'2016-03-04',500);
insert into income_tl values(1,'2016-03-05',500);

insert into income_tl values(2,'2016-03-01',200);
insert into income_tl values(2,'2016-03-02',300);
insert into income_tl values(2,'2016-03-03',300);
insert into income_tl values(2,'2016-03-04',500);
insert into income_tl values(2,'2016-03-05',400);

select it.user_id, 
       it.create_date, 
       it.income,
       case
          when @preVal = it.user_id then @curVal := @curVal + it.income
          when @preVal := it.user_id then @curVal := it.income
       end AS sum_income
from income_tl it, (select @preVal:=null, @curVal:=null) r
order by it.user_id asc, it.create_date asc;
运行结果为:


备注:

1. @preVal和@curVal相当于在sql的生命周期内声明了两个变量,一直有效。

2.第二个when仅用作为@preVal赋值,表示条件一直为true。(mysql中‘’、0、null均为false)

以上即为mysql中类似分析函数(开窗函数)的使用,欢迎指正,谢谢。

你可能感兴趣的:(mysql,分析函数,开窗函数,累加)