SQL SERVER 多列的最大值,最小值,平均值一次性查询

SQL SERVER 多列的最大值,最小值,平均值一次性查询

可以指定多列,其类型要一致,可以求其最大值,最小值,平均值等等。

采用 cross apply 关联字。具体如下:

select a.f0000,F0008,F0009,F0010,F0011,F0012,f0013,
f1 minf,f2 maxf,f3 avgf
 from te0001 a
 cross apply (
select MIN(f1) f1 from (
    select f0008 f1 from te0001 b where a.F0000=b.F0000 union
    select f0009 f1 from te0001 b where a.F0000=b.F0000 union
    select f0010 f1 from te0001 b where a.F0000=b.F0000 union
    select f0011 f1 from te0001 b where a.F0000=b.F0000 union
    select f0012 f1 from te0001 b where a.F0000=b.F0000 union
    select f0013 f1 from te0001 b where a.F0000=b.F0000
) d ) e
 cross apply (
select MAX(f2) f2 from (
    select f0008 f2 from te0001 b where a.F0000=b.F0000 union
    select f0009 f2 from te0001 b where a.F0000=b.F0000 union
    select f0010 f2 from te0001 b where a.F0000=b.F0000 union
    select f0011 f2 from te0001 b where a.F0000=b.F0000 union
    select f0012 f2 from te0001 b where a.F0000=b.F0000 union
    select f0013 f2 from te0001 b where a.F0000=b.F0000
 ) d ) f
 cross apply (
select avg(f3) f3 from (
    select f0008 f3 from te0001 b where a.F0000=b.F0000 union
    select f0009 f3 from te0001 b where a.F0000=b.F0000 union
    select f0010 f3 from te0001 b where a.F0000=b.F0000 union
    select f0011 f3 from te0001 b where a.F0000=b.F0000 union
    select f0012 f3 from te0001 b where a.F0000=b.F0000 union
    select f0013 f3 from te0001 b where a.F0000=b.F0000
 ) d ) g

说明:

-- 表te0001中,F0000是键值字段,F0008,F0009,F0010,F0011,F0012,f0013为decimal类型。

-- 别名 b 是必不可少的, cross apply要求指明表名(别名)
-- 别名 d 是必不可少的, 但每个子查询中的别名可以不同
-- 子查询中别名 f1,f2,f3 可以相同

 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值