我有这段代码:
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'
的列,而不是组合&#39;然后&#39;。例如,如果前2个案例为真,则列'casesCombined'
将为'"abc is larger than def", "def is larger than abc"'
。
像这样:
-----------------------------------------------------
| casesCombined |
-----------------------------------------------------
| 'abc is larger than def', 'def is larger than abc'|
-----------------------------------------------------
尝试了很多方法,但没弄清楚。我也不需要那些'case1'
,'case2'
...
答案 0 :(得分: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
子句时, ELSE
默认为NULL
concat_ws()
忽略NULL值。
我没有添加额外的单引号,因为我假设你实际上并不想要结果中的那些。如果您这样做,只需添加: