Reputation: 105
If I do something like
select max(case when col1 = 5 then 'banana' else '0')
how will SQL Server choose? What is the maximum value for the column?
Upvotes: 0
Views: 80
Reputation: 6130
I believe that when you do a MAX(string)
in SQL Server it orders the values alphabetically in an ascending order and picks the last value (bottom of the list)
Can you post the rest of your query? Or explain a bit more one what you are trying to achieve?
Upvotes: 1
Reputation: 56779
This is equivalent to taking data that looks like this:
col5
1
3
5
7
Then converting it to this
col5 | case when...
1 | 0
3 | 0
5 | banana
7 | 0
Then doing max on the above results. The result falls into four cases:
NULL
.col1 = 5
is true, then you will get banana
.col1 = 5
is false, then you will get 0
.col1 = 5
is true and false, you will get banana
, because banana > 0
according to lexicographical comparisonI have generally only seen this type of query when trying to do the equivalent of PIVOT without using the PIVOT statement.
Upvotes: 3