当前位置:网站首页>The combination of over clause and aggregate function in SQL Server

The combination of over clause and aggregate function in SQL Server

2022-07-07 09:54:00 knight_ hf

Here is an example from the Internet :

use tempdb
go
if (object_id ('tb' ) is not null )
    drop table tb
go
create table tb (name varchar (10 ), val int )
go
insert into tb
select 'aa' , 10
union all select 'aa' , 20
union all select 'aa' , 20
union all select 'aa' , 30
union all select 'bb' , 55
union all select 'bb' , 45
union all select 'bb' , 0

select *
, ranking = rank ()over (partition by name order by val )
, Proportion = cast (val * 1.0 / sum (val )over (partition by name ) as decimal (2 , 2 ))
, Maximum distance = val - max (val )over (partition by name )
, Minimum distance = val - min (val )over (partition by name )
, Distance average = val - avg (val )over (partition by name )
from tb

 

Through the example above , My own experience ( Not necessarily right , It's just convenient for you to understand ):

On the basis of the above example , If used directly select max(val) from tb group by name The query , return 2 That's ok .

If you use select max(val) over(partition by name) from tb Then return to 7 That's ok .

That is, after using the aggregate function , The window was opened again ( All the original rows in the table return ).

原网站

版权声明
本文为[knight_ hf]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130623570427.html