Max Value Per Row from a set of 100 Columns in SQL
While I have seen several answers to this question all of them tend to rely on on the greatest function which keeps coming back with a
"Msg 195, Level 15, State 10, Line 1 'GREATEST' is not a recognized built-in function name."
I would like to know a way to build a query that for each row returns the artifact id, and the greatest value in the row along with the column it was in. Any suggestions would be welcome. I've looked over quite a few example on this board and others but keep runnign across various errors.
Attempted and Failed Code, shortened for veiwing pleasure:
SELECT artifactID, GREATEST(V0,V1,V2,V3,V4,V5,V6...V98,V99) AS col_value,
CASE GREATEST(V0,V1,V2,V3,V4,V5,V6...V98,V99)
WHEN V0 THEN '0'
WHEN V1 THEN '1'
WHEN V2 THEN '2'
WHEN V3 THEN '3'
...
WHEN V99 THEN '99'
END AS col_nam开发者_如何学Ce
FROM dbo.Theta
Example of what I would like query to return:
ArtifactID GreatestColumnValue ColumnValueCameFrom
00001 .330 59
00002 .89 89
...
01000 .44 7
Thanks!
SELECT t.artifactID, c.col_value, c.col_name
FROM dbo.Theta t
OUTER APPLY
(SELECT TOP 1 *
FROM (
SELECT '0', V0 UNION ALL
SELECT '1', V1 UNION ALL
--...
SELECT '99', V99) X(col_name,col_value)
ORDER BY col_value desc) C
精彩评论