我有一个类似于以下的场景,我想要做的就是找到最多三列 - 这似乎是一个非常冗长的方法,我用来找到列mx
。
什么是更短的更优雅的解决方案?
CREATE TABLE #Pig
(
PigName CHAR(1),
PigEarlyAge INT,
PigMiddleAge INT,
PigOldAge INT
)
INSERT INTO #Pig VALUES
('x',5,2,3),
('y',2,9,5),
('z',1,1,8);
WITH Mx_cte
AS
(
SELECT PigName,
Age = PigEarlyAge
FROM #Pig
UNION
SELECT PigName,
Age = PigMiddleAge
FROM #Pig
UNION
SELECT PigName,
Age = PigOldAge
FROM #Pig
)
SELECT x.PigName,
x.PigEarlyAge,
x.PigMiddleAge,
x.PigOldAge,
y.mx
FROM #Pig x
INNER JOIN
(
SELECT PigName,
mx = Max(Age)
FROM Mx_cte
GROUP BY PigName
) y
ON
x.PigName = y.PigName
答案 0 :(得分:4)
SQL Server在接受值列表并返回最大值的其他RDBMS中没有等效的GREATEST
函数。
但是,您可以使用包含所需列的table valued constructor来模拟类似的内容,然后将MAX
应用于该列。
SELECT *,
(SELECT MAX(Age)
FROM (VALUES(PigEarlyAge),
(PigMiddleAge),
(PigOldAge)) V(Age)) AS mx
FROM #Pig
答案 1 :(得分:1)
如果您想要三个字段的最大值:
select (case when max(PigEarlyAge) >= max(PigMiddleAge) and max(PigEarlyAge) >= max(PigOldAge)
then max(PigEarlyAge)
when max(PigMiddleAge) >= max(PigOldAge)
then max(PigMiddleAge)
else max(PigOldAge)
end)
from #Pig
如果您要查找具有相应最大值的行,请使用row_number()
和union
:
select p.PigName, PigEarlyAge, PigMiddleAge, PigOldAge,
(case when PigEarlyAge >= PigMiddleAge and PigEarlyAge >= PigOldAge then PigEarlyAge
when PigMiddleAge >= PigOldAge then PigMiddleAge
else PigOldAge
end) as BigAge
from (select p.*,
row_number() over
(order by (case when PigEarlyAge >= PigMiddleAge and PigEarlyAge >= PigOldAge then PigEarlyAge
when PigMiddleAge >= PigOldAge then PigMiddleAge
else PigOldAge
end) desc
) seqnum as seqnum
from #Pig p
) p
where p.seqnum = 1;
如果您想要重复值,请使用rank()
代替row_number()
。
答案 2 :(得分:0)
如果您需要最多组合年龄,您可以在Max函数中简单地添加它们:
SELECT PigName, MAX(PigEarlyAge + PigMiddleAge + PigOldAge) as MaxAge
FROM #Pig
GROUP BY PigName