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

本文介绍三种SQL方法来查询包含多个时间记录列的数据表中每行的最小时间值。适用于SQL Server 2008 R2环境。方法包括:使用VALUES子句构建临时表、利用UNPIVOT进行行列转换及采用UNION ALL组合新表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

摘要:
  下文讲述通过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 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值