原表
A B C D
3 5 2 0
2 3 4 0
7 8 1 0
9 8 4 0
2 4 2 0如何得到
A B C D
3 5 2 5
2 3 4 4
7 8 1 8
9 8 4 9
2 4 2 4说明,这个功能在Excel中,使用Max可以很简单的得到,但是,在SQL
里面,Max是记录与记录里面的比较,怎么得到列与列之间比较得到的
最大值呢?感谢。
A B C D
3 5 2 0
2 3 4 0
7 8 1 0
9 8 4 0
2 4 2 0如何得到
A B C D
3 5 2 5
2 3 4 4
7 8 1 8
9 8 4 9
2 4 2 4说明,这个功能在Excel中,使用Max可以很简单的得到,但是,在SQL
里面,Max是记录与记录里面的比较,怎么得到列与列之间比较得到的
最大值呢?感谢。
case when a>=b then case when a>=c then c else a end else case when b>=c then b else c end as d
from tb[/code]
a,b,c ,
case when a>=b then
case when a>=c then c else a end
else
case when b>=c then b else c end
as d
from tb
要函数得自己写个
/*
oracle中有greatest()和least()函数。
但是ms-sql中没有。
*/
create function Greatest(@i int ,@j int)
returns int
as
begin
if(@i>@j)
return @i
else
return @j
return 0
end
go
declare @原表 table (A int,B int,C int)
insert into @原表
select 3,5,2 union all
select 2,3,4 union all
select 7,8,1 union all
select 9,8,4 union all
select 2,4,2select *,dbo.Greatest(dbo.Greatest(a,b),c) as d from @原表/*
A B C d
----------- ----------- ----------- -----------
3 5 2 5
2 3 4 4
7 8 1 8
9 8 4 9
2 4 2 4
*/
create table tb(a int,b int,c int,d int)
insert into tb
select 3,5,2,0 union all
select 2,3,4,0 union all
select 7,8,1,0 union all
select 9,8,10,0 union all
select 2,4,2,0 update tb set d=(case when (case when a>b then a else b end)>c
then ((case when a>b then a else b end)) else c end)
select * from tb
/*
a b c d
----------- ----------- ----------- -----------
3 5 2 5
2 3 4 4
7 8 1 8
9 8 10 10
2 4 2 4
if object_id('tempdb.dbo.#') is not null drop table #
create table #(A int, B int, C int, D int)
insert into #
select 3, 5, 2, 0 union all
select 2, 3, 4, 0 union all
select 7, 8, 1, 0 union all
select 9, 8, 4, 0 union all
select 2, 4, 2, 0select A,B,C,D=
(
select max(A) from
(
select A union all
select B union all
select C
) t
)
from #/*
A B C D
----------- ----------- ----------- -----------
3 5 2 5
2 3 4 4
7 8 1 8
9 8 4 9
2 4 2 4
*/