我在sql2005中创建了一个名为cs的表,里面有5列,分别是Number,x1,x2,x3,x4,我想问一下如何用Max来求每一行中的x1,x2,x3,x4四个数的最大值啊,我试着用Max(x1,x2,x3,x4),但是系统提示Max只能用一个参数,求高手啊!!!!!!!!!!!!
------解决方案--------------------
试试这个:
select Number,x1,x2,x3,x4,
case when X1 >= x2 and x1 >= x3 and X1>= x4 then x1
when X2 >= x1 and x2 >= x3 and X2>= x4 then X2
when X3 >= x1 and x3 >= x2 and X3>= x4 then X3
else X4
end '最大值'
from cs
------解决方案--------------------
照理应该是可以显示的,把那个字段改成maxvalue试试:
select Number,x1,x2,x3,x4,
case when X1 >= x2 and x1 >= x3 and X1>= x4 then x1
when X2 >= x1 and x2 >= x3 and X2>= x4 then X2
when X3 >= x1 and x3 >= x2 and X3>= x4 then X3
else X4
end maxvalue
from cs
如果还需要存储,那么就需要insert 语句,插入到一个表中
------解决方案--------------------
5个列穷举都不会很多
------解决方案--------------------
--假設x5字段保存最大值
WITH a1 AS
(
SELECT *
FROM cs a
CROSS APPLY
(
SELECT MAX(x1)
FROM
(
SELECT x1 AS maxvalue FROM cs WHERE Number=a.Number
UNION
SELECT x2 FROM cs WHERE Number=a.Number
UNION
SELECT x3 FROM cs WHERE Number=a.Number
UNION
SELECT x4 FROM cs WHERE Number=a.Number
) b
) c
UPDATE a1 SET x5=maxvalue
------解决方案--------------------
--5樓少一個括號
--假設x5字段保存最大值
WITH a1 AS
(
SELECT *
FROM cs a
CROSS APPLY
(
SELECT MAX(x1)
FROM
(
SELECT x1 AS maxvalue FROM cs WHERE Number=a.Number
UNION
SELECT x2 FROM cs WHERE Number=a.Number
UNION
SELECT x3 FROM cs WHERE Number=a.Number
UNION
SELECT x4 FROM cs WHERE Number=a.Number
) b
) c
)
UPDATE a1 SET x5=maxvalue