WITH base AS (
SELECT 'ID1' as id, 0 as foo
UNION
SELECT 'ID1' as id, -1 as foo
UNION
SELECT 'ID2' as id, 2 as foo
UNION
SELECT 'ID2' as id, null as foo
UNION
SELECT 'ID2' as id, -1 as foo
UNION
SELECT 'ID2' as id, 1 as foo
)
select
id
,MAX(CASE WHEN char_length(foo) > 0 THEN foo ELSE NULL END)
from base
GROUP BY id
ORDER BY id ASC
This query returns 0 for the ID1 and 2 for the ID2.
What I'd like to have, is a SELECT expression that's going to return -1 for the ID1 and 2 for the ID2.
MAX(ABS())
is almost what I want, but it returns 1
and not -1
. I can't use JOIN and anything else, only a SELECT expression. Any ideas?
Here is one way to solve it:
select
id
,MAX(ABS(foo)) * CASE WHEN ABS(MIN(foo)) > MAX(foo) THEN -1 ELSE 1 END As MaxAbs
from base
GROUP BY id
ORDER BY id ASC
Results:
id MaxAbs
ID1 -1
ID2 2
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.