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 可以相同