日期:2014-05-19  浏览次数:20520 次

怎样取同一个记录中各个字段中的最大值
例如:
8   6   9
5   4   1


9   5

MAX只能取字段中最大值不是一条记录中

------解决方案--------------------
create table test(
id int,
a int,
b int,
c int
)
declare @t table(id int,num int)
insert into test
select 1,8,6,9 union all
select 2,5,4,1

insert into @t
select id,a as num from test
union all
select id,b as num from test
union all
select id,c as num from test

select max(num) from @t group by id

drop table test


----结果----------
1 9
2 5


是这样?
------解决方案--------------------
declare @table_pqs table(id int,num1 int,num2 int,num3 int)
insert into @table_pqs
select 1,8,6,9 union all
select 2,5,4,1


select case when num1> =num2 and num1> =num3 then num1
when num2> num1 and num2> =num3 then num2
when num3> num1 and num3> num2 then num3
end as max
from @table_pqs
------解决方案--------------------
引用:
declare @table_pqs table(id int,num1 int,num2 int,num3 int)
insert into @table_pqs
select 1,8,6,9 union all
select 2,5,4,1


select case when num1> =num2 and num1> =num3 then num1
when num2> num1 and num2> =num3 then num2
when num3> num1 and num3> num2 then num3
end as max
from @table_pqs

为什么上面的语句在我这边的机子上显示

服务器: 消息 137,级别 15,状态 2,行 5
必须声明变量 '@table_pqs '。

这样的错误啊!
------解决方案--------------------
寫個交叉表查詢,使表行列換過來,
#t
col1 col2
7 8
9 3
2 7
然後 select a = (select max(col1) from #t),b = (select max(col2) from #t)
------解决方案--------------------
不怕影响速度
可以行转列
然后
select max(?),max(??),...