MSSQL 多字段根据范围求最大值实现方法
2009-09-21 00:00
555 查看
-->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
*/
-->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
*/
相关文章推荐
- MSSQL多字段根据范围求最大值
- ORACLE 连接某个字段及分组后取某个字段最大(最小)等实现方法
- MSSQL根据ID进行分页实现方法
- mssql存储过程表名和字段名为变量的实现方法
- Python编程实现生成特定范围内不重复多个随机数的2种方法
- 修改php.ini实现Mysql导入数据库文件最大限制的修改方法
- php和mysql采用utf-8编码时实现按照一个文本字段的首字母的拼音顺序进行排序的方法
- php mssql扩展SQL查询中文字段名解决方法
- 利用sql2005的新特性实现根据子表条件得到的主表键且按其排序取出对应主子表记录的方法
- PHP实现根据数组某个键值大小进行排序的方法
- GPS定位,根据经纬度查询附近地点的经纬度-sql方法实现
- SQL字符型字段按数字型字段排序实现方法
- thinkphp mysql 字段区间查询 根据范围筛选字段
- 查询MYSQL表字段最大值的方法
- 用三种方法实现最大子列和的求解(Python实现)
- 最大公约数(公因子)多种java实现方法
- 【日记】利用VB.NET实现MYSQL和MSSQL进行批量插入记录的方法及比较
- js判断出两个字符串最大子串的函数实现方法