我有一个类似于以下的场景,我想做的就是找到三列的最大值 - 这似乎是我用来查找列的一个非常冗长的方法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