I've been having an interesting conversation with some coworkers about how to solve the following problem. Suppose I have a table with the following columns:
foo_1,foo_2, foo_3, field_etc, Score1, Score2, Score3, Score4, Score5, MoreFields, MoreScores, EvenMoreScores
I need to build a query which returns the following:
foo_1, foo_2, foo_3, field_etc, MaxScore
Where MaxScore is the maximum value between Score1, Score2, Score3, Score4, Score5
What we have is something like this:
SELECT
foo_1, foo_2, foo_3, field_etc,
(
SELECT MAX(foo) as Something
FROM
(
SELECT SomeTable.Score1 AS foo
UNION ALL
SELECT SomeTable.Score2
UNION ALL
SELECT SomeTable.Score3
UNION ALL
SELECT SomeTable.Score4
UNION ALL
SELECT SomeTable.Score5
) AS x
) AS MaxScore
FROM
SomeTable
I feel like there should be a cleaner way to do this but we have not found one. We are avoiding the obvious UDF solution for performance reasons.
Would be great if there were some kind of range function in tsql so I could do:
SELECT
foo_1, foo_2, foo_3, field_etc, MAX(Score1, Score2, Score3, Score4, Score5) as MaxScore
FROM
SomeTable
Ideally the underlying table would be normalized and this wouldn't be a problem but I don't have the ability to change it here.