MSSQL 多字段根据范围求最大值实现方法

时间:2021-05-24

-->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]

--方法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

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章