mssql sqlserver 获取数据表中一行中多列中列中的最大值的方法分享


摘要:
下文讲述通过sql脚本获取一个数据表中,多列数据中最大列值数据的方法
实验环境:sqlserver 2008 R2


例:
当我们建立一张数据表存储三台设备生产一个同样工序所需的时间,
先我们需获取每次生产的最短时间

   
 create table test
   (name varchar(10),time1 int,time2 int,time3 int)
    insert into test (name,time1,time2,time3)
	values
	('a',1,2,3),	('b',8,9,6),	('c',11,22,8),	('d',101,201,38),
	('e',6,7,9),	('f',8,8,13),	('g',2,2,30),	('h',82,56,53)
   go

 ---方法1:使用values子句构建临时表 

select name,(select min(timeMin) from (values (time1),(time2),(time3)) as #temp(timeMin)) as timeMin from test
 
---方法2 行转列

select name, min(timeMin) as [最小数] from test unpivot (timeMin for timeMint in (time1,time2,time3)) as u group by name
 
--方法3:使用 union all组合新表 
select name, (select min(timeMin) 
as [最小数] from (
select test.time1 as timeMin
 union all 
 select test.time2 
 union all  
 select test.time3) ud) 
 MaxDate from test 

 go

  
mssql_sqlserver_获取列最小值的方法

mssql_sqlserver_获取列最小值的方法