MSSQL 多字段根据范围求最大值实现方法
-->Title:生成測試數據
-->Author:wufeng4552
-->Date :2009-09-21 15:08:41
declare @T table([Col1] int,[Col2] int,[Col3] int,[Col4] int,[Col5] int,[Col6] int,[Col7] int)
Insert @T
select 1,10,20,30,40,50,60 union all
select 2,60,30,45,20,52,85 union all
select 3,87,56,65,41,14,21
--方法1
select [col1],
max([col2])maxcol
from
(select [col1],[col2] from @t
union all
select [col1],[col3] from @t
union all
select [col1],[col4] from @t
union all
select [col1],[col5] from @t
union all
select [col1],[col6] from @t
union all
select [col1],[col7] from @t
)T
where [col2] between 20 and 60 --條件限制
group by [col1]
/*
col1 maxcol
----------- -----------
1 60
2 60
3 56
(3 個資料列受到影響)
*/
--方法2
select [col1],
(select max([col2])from
(
select [col2]
union all select [col3]
union all select [col4]
union all select [col5]
union all select [col6]
union all select [col7]
)T
where [col2] between 20 and 60) as maxcol --指定查詢範圍
from @t
/*
(3 個資料列受到影響)
col1 maxcol
----------- -----------
1 60
2 60
3 56
*/
相关文章
SQL Server利用bcp命令把SQL语句结果生成文本文件
在SQL Server里可以调用DOS下的命令行工具bcp来实现把表里的数据或者SQL语句结果生成文本文件,详细看下操作方法,感兴趣的你可不要错过了哈2013-02-02
case when then else end语句的用法(附demo)
本文主要介绍了case when then else end语句的用法,主要介绍了两种格式,简单case函数和case搜索函数,具有一定的参考价值,感兴趣的可以了解一下2023-10-10
远程连接局域网内的sql server 无法连接 错误与解决方法
下面我们依次介绍如何来解决这三个最常见的连接错误。2009-09-09
SQL Server 使用触发器(trigger)发送电子邮件步骤详解
本文分步骤给大家详细介绍了SQL Server 使用触发器(trigger)发送电子邮件的方法,需要的朋友可以参考下2017-04-04


最新评论