2015-10-28 41 views
1

我有這樣的代碼:列的複雜串聯成一列

SELECT DISTINCT 
CASE 
    WHEN abc > def THEN 'abc is larger than def'::text 
    ELSE NULL::text 
END AS case1, 
CASE 
    WHEN abc < ghi THEN 'def is larger than abc'::text 
    ELSE NULL::text 
END AS case2, 
CASE 
    WHEN abc > jkl THEN 'abc is larger than jkl'::text 
    ELSE NULL::text 
END AS case3, 

這看起來是這樣的:

------------------------------------------------------------------------------------- 
|    case1   |   case2   |   case3   | 
------------------------------------------------------------------------------------- 
| 'abc is larger than def' | 'def is larger than abc' | 'abc is larger than jkl' | 
------------------------------------------------------------------------------------- 

我想要做的就是創建一個名爲'casesCombined'列,比將結合「然後是」。例如,如果前2個案例屬實,則列'casesCombined'將爲'"abc is larger than def", "def is larger than abc"'

像這樣:

----------------------------------------------------- 
|     casesCombined     | 
----------------------------------------------------- 
| 'abc is larger than def', 'def is larger than abc'| 
----------------------------------------------------- 

嘗試過很多辦法,沒能搞清楚。我也當沒有ELSE條款不需要這些'case1''case2' ...

回答

0
SELECT concat_ws(', ', CASE WHEN abc > def THEN 'abc is larger than def' END 
        , CASE WHEN abc < ghi THEN 'def is larger than abc' END 
        , CASE WHEN abc > jkl THEN 'abc is larger than jkl' END 
       ) AS cases_combined 
FROM tbl; 

CASE默認爲NULL。
concat_ws()忽略空值。

我沒有添加額外的單引號,因爲我假設你實際上並不想要這些結果。只需添加,如果你這樣做:

+0

它的工作!謝謝,歐文。 –