利用函数逐行对表进行求最大数、最小数、N个最大数的平均值、N个最小数的平均值

--利用函数逐行对表进行求最大数、最小数、N个最大数的平均值、N个最小数的平均值
if OBJECT_ID('t') is not null
  drop table t
go

create table t
(
col1 decimal(18,4),
col2 decimal(18,4),
col3 decimal(18,4),
col4 decimal(18,4),
col5 decimal(18,4)
)
go

insert into t
select 3.25,5.46,6.86,45.26,21.35
union all
select 23.26,15.37,26.46,58.19,25.64
union all
select 56.13,28.34,19.46,98.10,46.82
go

if OBJECT_ID('fun_min') is not null
  drop function fun_min
go

--求表每行最小值
create function fun_min(@col1 decimal(18,4),@col2 decimal(18,4),@col3 decimal(18,4),@col4 decimal(18,4),@col5 decimal(18,4))
  returns decimal(18,4)
as
  begin
    declare @t table(col decimal(18,4))
    insert into @t
    select @col1
    union all
    select @col2
    union all
    select @col3
    union all
    select @col4
    union all
    select @col5
   
    return (select min(col) from @t)
    --每行最大值
    --return (select max(col) from @t)
  end
go

select dbo.fun_min(col1,col2,col3,col4,col5) from t
go

if OBJECT_ID('fun_avg') is not null
  drop function fun_avg
go

--求表每行前三个最大数平均值
create function fun_avg(@col1 decimal(18,4),@col2 decimal(18,4),@col3 decimal(18,4),@col4 decimal(18,4),@col5 decimal(18,4))
returns decimal(18,4)
as
begin
declare @t table(col decimal(18,4))
insert into @t
select @col1
union all
select @col2
union all
select @col3
union all
select @col4
union all
select @col5

return (select avg(col) from (select top 3 col from @t order by col desc) a)
--求表每行前三个最小数平均值
--return (select avg(col) from (select top 3 col from @t order by col asc) a)
end
go

select dbo.fun_avg(col1,col2,col3,col4,col5) from t
go

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值