2017-05-24 101 views
0
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 

此查詢返回ID1的2和ID2的2。SQL:選擇原始最高絕對值

我想要的是一個SELECT表達式,它將爲ID1返回-1,爲ID2返回2。

MAX(ABS())幾乎是我想要的,但它返回1而不是-1。我不能使用JOIN和其他任何東西,只有一個SELECT表達式。有任何想法嗎?

+0

凡在你的CTE做列稱爲'ID1'和'ID2'出現? –

+0

@TimBiegeleisen沒有列ID1和ID2。這些是「id」列的值。我改變了值,所以它不那麼容易混淆。 –

+0

如果多個ID具有最大foo值,會發生什麼情況? –

回答

2

這是解決這個問題的一種方法:

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 

結果:

id  MaxAbs 
ID1  -1 
ID2  2