当前位置: 首页 > 图文教程 > 数据库 > MSSQL > 用一条SQL实现:一行多个字段数据的最大值

MSSQL
开源MySQL公司停止提供企业版源代码tar包
细化解析:MySQL+Webmin轻松创建数据库
用mysql做站点时怎样记录未知错误的发生
SQL数据库操作类
如何利用SQL Server数据库快照形成报表
SQL Server中应当怎样得到自动编号字段
SQL Server数据库连接中常见的错误分析
详细讲解SQL Server数据库的文件恢复技术
轻松掌握SQL Server数据库的六个实用技巧
SQL Server数据库涉及到的数据仓库概念
深入了解SQL Server 2008 商业智能平台
剖析SQL Server 事务日志的收缩和截断
如何在不同版本的SQL Server中存储数据
怎样缩小SQL Server数据库的日志文件
SQL Server中两种修改对象所有者的方法
轻松掌握SQL Server存储过程的命名标准
怎样从旧版本SQL Server中重新存储数据
快速掌握如何使用SQL Server来过滤数据
教你快速掌握两个SQL Server的维护技巧
有效地使用 SQL事件探查器的提示和技巧

MSSQL 中的 用一条SQL实现:一行多个字段数据的最大值


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-10-17   浏览: 94 ::
收藏到网摘: n/a

原问题是这样的:如何用SQL语句(不是Oracle),求出下表每一行的5个字段中的最大值,最后生成一个新字段。

例如:

第一行最大值 -5.0 (c字段) 空值忽略

第二行最大值 -5.5 (a字段) 空值忽略

ab c d e

-21.5-15.0-5.0

-5.5-11.5

-5.0-16.5-10.5

-9.0

-11.5-14.0-8.5

-10.5-11.0-15.5-14.0-12.5

-15.0-11.0-10.5-17.0

-12.5-8.0-14.5

-8.0-12.0

-6.5-11.5-19.5-22.5-20.0

-13.0-7.5-14.0

-8.0-12.0-12.0

。。。。。。

解决方法如下:

1create table T(A decimal(10,1), B decimal(10,1), C decimal(10,1), D decimal(10,1), E decimal(10,1))

2insert T select -21.5,-15.0,-5.0, null, null

3union all select -5.5,-11.5,null, null, null

4union all select -1.0,-16.5,-10.5, null, null

5

6

7select *,

8max_value=(

9select max(A) from

10(

11select A

12union all

13select B

14union all

15select C

16union all

17select D

18union all

19select E

20)tmp)

21from T

22

--result

A B C D E max_value

------------ ------------ ------------ ------------ ------------ ------------

-21.5 -15.0 -5.0 NULL NULL -5.0

-5.5 -11.5 NULL NULL NULL -5.5

-1.0 -16.5 -10.5 NULL NULL -1.0

(3 row(s) affected)

这一方法,自我感觉不错,还真的第1次看到这样的写法。原来SQL里面还可以实现这样的写法,又学到了一点知识。