本文转载,地址:https://blog.csdn.net/dwt1415403329/article/details/87835383
因为over是开窗函数,mysql不支持开窗函数,其他如oracle,sql server,db2…等新版本都支持
CREATE TABLE Employee
(
ID number(10) not null primary key,
EmpName varchar(20),
EmpSalary varchar(10),
EmpDepartment varchar(20)
);
insert all into Employee values(1,'张三','5000','开发部')
into Employee values(2,'李四','2000','销售部')
into Employee values(3,'王麻子','2500','销售部')
into Employee values(4,'张三表叔','8000','开发部')
into Employee values(5,'李四表叔','5000','开发部')
into Employee values(6,'王麻子表叔','5000','销售部')
select 1 from dual
SELECT EmpDepartment,SUM(EmpSalary) sum_sala FROM Employee GROUP BY EmpDepartment
SELECT EmpSalary,EmpDepartment,SUM(EmpSalary) OVER(PARTITION BY EmpDepartment) sum_sala FROM Employee
小结:
group by 和 partition by 都有分组统计的功能,但partition by并没有group by的汇总功能。
partition by统计的每一条记录都存在,而group by将所有的记录汇总成一条记录(类似于distinct EmpDepartment 去重)。
partition by可以和聚合函数结合使用,同时具有其他高级功能。
SELECT EmpSalary,EmpDepartment,SUM(EmpSalary) OVER(PARTITION BY EmpDepartment ORDER BY EmpSalary) sum_sala FROM Employee
加上order by 后,类似于累加功能(sum_sala = sum_sala + EmpSalary)
先观察销售部的结果:
第4条记录: sum(EmpSalary)即sum_sala=2000,
第5条记录: sum(EmpSalary)=sum_sala+2500=4500,
即第4条sum_sala与第5条EmpSalary的和,依次类推;
开发部:
由于2个5000是并列的,所以计算的时候是几个并列数据之和即5000+5000=10000。
with t1 as (select * from (
select a.group_id,a.ap_start_date ,a.row_id, row_number() over(partition by t.group_Id order by t.TASK_DATE desc) mm
from em_task t
left join Em_Re_Group a on a.task_id = t.row_id where t.task_Type in( '1' ,'4') and t.status_Flag = '9'
and t.c_Status_Flag = '4' and t.deleted_flag = '0') tt where mm = 1)
select q.dealer_code,t1.group_id,q.dealer_name,t1.ap_start_date from dm_dealer q, t1 where q.group_id = t1.group_id;