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

所属分类: 数据库 / MsSql 阅读数: 1923
收藏 0 赞 0 分享

-->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 Substring提取部分字符串

SQL 中的 substring 函数是用来抓出一个栏位资料中的其中一部分。这个函数的名称在不同的资料库中不完全一样
收藏 0 赞 0 分享

用户"sa"登陆失败 SQLServer 错误18456的解决方法

sqlserver下用sa登录提示18456错误的解决方法。
收藏 0 赞 0 分享

drop,truncate与delete的区别

这里说的delete是指不带where子句的delete语句
收藏 0 赞 0 分享

SQL语句查询数据库中重复记录的个数

一个sql语句:一个表test有四个字段id,a,b,c,如果表中的记录有三个字段a,b,c都相等,则说明这条记录是相同的,求相同的记录的个数 。
收藏 0 赞 0 分享

SQL 导入导出Excel数据的语句

从Excel文件中,导入数据到SQL数据库中,很简单
收藏 0 赞 0 分享

可以获取客户端的IP地址的sql语句

利用SQL语句得到客户端的IP地址的代码
收藏 0 赞 0 分享

SQL 根据汉字获取全拼的代码

SQL 根据汉字获取全拼(有些字还没有添加上去,请自已加上去,涂聚文注)
收藏 0 赞 0 分享

sqlserver exists,not exists的用法

exists,not exists的使用方法示例,需要的朋友可以参考下。
收藏 0 赞 0 分享

sqlserver substring函数使用方法小结

在操作sqlserver时候用到了substring函数,特整理一些实例,需要的朋友可以参考下。
收藏 0 赞 0 分享

sql 判断数据库,表,存储过程等是否存在的代码

sql下用了判断各种资源是否存在的代码,很实用。需要的朋友可以参考下。
收藏 0 赞 0 分享
查看更多