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
	('猫猫小屋',1,2,3),	('sql教程专用',8,9,6),	('c',11,22,8),	('d',101,201,38),
	('e',6,7,9),	('maomao365',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
truncate table test
drop table test 

猜你喜欢

转载自blog.csdn.net/qq_25073223/article/details/81776971