sql 查询一行内几列的平均值,最大值,最小值,怎么写

比如 name 1 2 6 7 9 0 3 求 1,2,6,7,9,0,3这几个值的最大最小平均值
2025-01-07 03:07:35
推荐回答(5个)
回答1:

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

回答2:

select AVG(name),MAX(name),MIN(name) from 表

回答3:

max min avg

回答4:

如图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;

之后会如下图效果:

这是最大值的,平均值就是换个函数名你应该可以看得到

回答5:

列数固定的还是不固定的?