如题,怎么让结果MaxValue显示为最大的那个数“7”?
--建表
declare @t table(
a int,
b int,
c int,
d int,
e int,
f int
)
--插数据
insert into @t select 5,6,4,1,7,5--显示最大值。这行如何实现?
select max(a,b,c,d,e,f) as MaxValue, * from @t

解决方案 »

  1.   

    MSSQL多列取最大或者最小值
      

  2.   

    以前三个数比较的时候可以用下面的方法,但超过四个数就不能这么比了。
    select (case when (a >= b) then a when (b >= c) then c else d end) from @t
      

  3.   

    哈,谢了。下面是正确的测试结果:
    declare @t table(id int, a int, b int, c int, d int, e int, f int)insert into @t select 1, 5,6,4,1,7,5 --7
    insert into @t select 2, 1,6,4,1,7,8 --8
    insert into @t select 3, 8,6,4,1,7,1 --8
    insert into @t select 4, 5,6,8,1,7,5 --8
    insert into @t select 5, 5,5,5,5,5,5 --5select * from @tselect a.id,
    (select max(a) from (
    select a from @t where id=a.id
    union all select b from @t where id=a.id
    union all select c from @t where id=a.id
    union all select d from @t where id=a.id
    union all select e from @t where id=a.id
    union all select f from @t where id=a.id
    ) bbb)
    from @t a
      

  4.   

    看来我想的还更复杂,再仔细看看老本家(wu开头的名字)的帖子,对比一下居然还可以这样写:
    declare @t table(id int, a int, b int, c int, d int, e int, f int)insert into @t select 1, 5,6,4,1,7,5 --7
    insert into @t select 2, 1,6,4,1,7,8 --8
    insert into @t select 3, 8,6,4,1,7,1 --8
    insert into @t select 4, 5,6,8,1,7,5 --8
    insert into @t select 5, 5,5,5,5,5,5 --5select * from @tselect a.id,
    (select max(a) from (
    select a --from @t where id=a.id
    union all select b --from @t where id=a.id
    union all select c --from @t where id=a.id
    union all select d --from @t where id=a.id
    union all select e --from @t where id=a.id
    union all select f --from @t where id=a.id
    ) bbb)
    from @t a
      

  5.   

    select case when a > b and a > c and a > d and a > e and a > f then a
                when b > a and b > c and b > d and b > e and b > f then b
                ...
           end
    from @t