oracle的话直接用greatest函数,sql server的话照这么写:
select t1.name, max(t1.a) maxnum,min(t1.a) minnum,avg(t1.a) avgnum from
(select name,num1 a from tb1
union all
select name,num2 a from tb1
union all
select name,num3 a from tb1
union all
select name,num4 a from tb1
union all
select name,num5 a from tb1
union all
select name,num6 a from tb1
union all
select name,num7 a from tb1) t1
group by t1.name;
测试数据:
create table tb1(name varchar(50),num1 int,num2 int,num3 int,num4 int,num5 int,num6 int,num7 int)
insert into tb1 select 'Tom',1,2,6,7,9,0,3
insert into tb1 select 'Jacky',7,6,5,4,3,2,1
结果:
name maxnum minnum avgnum
Jacky 7 1 4
Tom 9 0 4
select AVG(name),MAX(name),MIN(name) from 表
max min avg
如图2个列的数据,通过下面的sql来查询出每个ID的最大值在一条记录(行)中:
SELECT
id, MAX(max_data) FROM (SELECT id, data1 as max_data FROM 表名 UNION
SELECT id, data2 FROM 表名) MaxData(必须再自定义一个表名) GROUP BY id;
之后会如下图效果:
这是最大值的,平均值就是换个函数名你应该可以看得到
列数固定的还是不固定的?