日期:2014-05-17  浏览次数:20533 次

取最大值问题
有这样一张表格:

Table1:

ID   Past  Now  Future
1    0     1    5
2    1     3    0
3    2     4    3

怎样取出ID和(Past、Now、Future)中的最大值,SQL语句怎么写啊?

ID Max
1  5
2  3
3  4
SQL

------解决方案--------------------
给你这么一个语句,自己构造去吧
select max(id) from(select id=0 union all select 1 union all select 5)a
------解决方案--------------------
create table Table1(ID int,  Past int, Now int, Future int)
insert into table1 values(1 ,   0  ,   1  ,  5)
insert into table1 values(2 ,   1  ,   3  ,  0)
insert into table1 values(3 ,   2  ,   4  ,  3)
go

select id , case when Past >= Now and Past >=Future then Future
                 when Now >= past and Now >=Future then Now
                 when Future>=Past and Future >=Now then Future
            end [Max]
from table1 

/*
id          Max         
----------- ----------- 
1           5
2           3
3           4

(所影响的行数为 3 行)
*/

select id , max([max]) [max] from 
(
select id , now [max] from table1
union all
select id , now [Now] from table1
union all
select id , Future [max] from table1
) t
group by id
/*
id          Max         
----------- ----------- 
1           5
2           3
3           4

(所影响的行数为 3 行)
*/


drop table table1

------解决方案--------------------
select id,max(cl) as [Max] from(select id,past as cl from tb union all select id,[now]as cl from tb union all select id,future as cl from tb)t
------解决方案--------------------
个人觉得用 select case when 方式吧,
好理解些,
呵呵
------解决方案--------------------