Welcome user: Felipe
The doc's seem to describe the results exactly:
Returns the largest value from a list of expressions. If any of the argument values is NULL, the result is NULL. GREATEST supports all data types, including VARIANT.
If you ORDER BY data, NULL
is last, GREATEST is returning the LAST value..
Snowflake is rather consistent
select
a,b,c
,greatest(a, b) as g_a_b
,greatest(a, c) as g_a_c
,greatest(b, c) as g_b_c
from values
(1.1, 2.3, null::float),
(null, 2, 3.5),
(1, null, 3),
(null, null, null)
t(a,b,c)
gives:
A |
B |
C |
G_A_B |
G_A_C |
G_B_C |
1.1 |
2.3 |
null |
2.3 |
null |
null |
null |
2 |
3.5 |
null |
null |
3.5 |
1 |
null |
3 |
null |
3 |
null |
null |
null |
null |
null |
null |
null |
so your min value -inf
solution is interesting/gross, I mean it's correct.
But what GREATEST is doing is handling a fixed number of SQL declared columns, so the NVL soltuion works: But to make a generic solution, building the fix arrays, and then flattening, and the maxing as max handles NULL in the implicit way the problem implies which "them not being selected"
select a,b,c, max(f.value)
from (
select
a,b,c
,array_construct_compact(a, b, c) as aa
from values
(1.1, 2.3, null),
(null, 2, 3.5),
(1, null, 3),
(null, null, null)
t(a,b,c)
), table(flatten(input=>aa)) as f
group by 1,2,3,f.seq
gives:
A |
B |
C |
MAX(F.VALUE) |
1 |
null |
3 |
3 |
null |
2 |
3.5 |
3.5 |
1.1 |
2.3 |
null |
2.3 |