一条SQL语句实现:一行多个字段数据的最大值。

原帖:http://community.csdn.net/Expert/topic/5403/5403570.xml?temp=.6892511

原问题是这样的:如何用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
。。。。。。



在回帖中发现有一方法不错,那就是marco08(天道酬勤) 的回帖,如下:

 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.0nullnull
 3union all select -5.5,-11.5,nullnullnull
 4union all select -1.0,-16.5,-10.5nullnull
 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里面还可以实现这样的写法,又学到了一点知识。


posted @ 2007-03-19 12:55  ok_008  阅读(6198)  评论(3编辑  收藏  举报
给我写信