mysql 实现oracle的分析函数

@的用户变量用户变量用法:
转:
https://mp.csdn.net/postedit
1、if函数 
if(condition,a,b) :当condition为真的时候返回a,否则返回b
作为条件语句使用 以t_check_user为例:
select if (check_user_status=1,1,if(check_user_status=2,999,9)) from t_check_user;
当check_user_status=1的时候返回1,当check_user_status=2的时候返回999,否则返回9
2、mysql将查询结果添加序号
第一种方法:
select check_user_status,@rn := @rn + 1 AS rn from  t_check_user,(select @rn:=0) as it;
第二种方法:每次查询必须一起执行,rn才能从1开始,否则每次从最后一个序号开始递增
set @rn:=0;
select check_user_status,@rn := @rn + 1 AS rn from  t_check_user;
3、mysql分组求和对于oracle sum() over()
方法一:

求每个月的销售额及累计销售额(二月份额累计销售额是一月销售额加二月销售额)
oracle写法:
实验数据:表sale
| month  | user_id | amount |
+--------+---------+--------+
| 201601 | 1       |    500 |
| 201601 | 2       |    300 |
| 201601 | 3       |    100 |
| 201602 | 1       |   1000 |
| 201602 | 2       |    800 |
| 201603 | 2       |   1000 |
| 201603 | 3       |    500 |
| 201604 | 1       |   1000 |
select 
a.month,a.amount,sum(b.amount) 
from (select month,sum(amount) amount from sale GROUP BY month) a CROSS JOIN (select month,sum(amount) amount from sale GROUP BY month) b 
where a.month>=b.month GROUP BY a.month,a.amount;

等价于mysql写法:select a.month_a,a.amount_a,sum(b.amount_b) from 
(select month month_a,sum(amount) amount_a from sale GROUP BY month_a) a CROSS JOIN (select month month_b,sum(amount) amount_b from sale GROUP BY month_b) b where a.month_a>=b.month_b 
group by a.month_a,a.amount_a
order by month_a;
结果表:

 month  | sum  | sum  
--------+------+------
 201601 |  900 |  900
 201602 | 1800 | 2700
 201603 | 1500 | 4200
 201604 | 1000 | 5200
方法二:
4、max()over()函数mysql实现
方法一:
每一行显示最大销售额

 SELECT
IF
    ( @max_amount = 0, @max_amount := amount, (select max(mount) from sale)) AS max_amount
FROM
    sale  a,(select @max_amount=1) as it;
方法二:

5、特殊的行转列
每一列显示每个月的销售额最大值



 


 

猜你喜欢

转载自blog.csdn.net/qq_24726509/article/details/82633719