将列复杂串联成一列
Complex concatenation of columns into one column
我有这个代码:
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'
的列,而不是合并“then's”。例如,如果前 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'
...
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;
当没有 ELSE
子句时,CASE
默认为 NULL。
concat_ws()
忽略 NULL 值。
我没有添加额外的单引号,因为我假设您实际上并不想要结果中的那些。如果您这样做,只需添加:
- Insert text with single quotes in PostgreSQL
我有这个代码:
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'
的列,而不是合并“then's”。例如,如果前 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'
...
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;
当没有 ELSE
子句时,CASE
默认为 NULL。
concat_ws()
忽略 NULL 值。
我没有添加额外的单引号,因为我假设您实际上并不想要结果中的那些。如果您这样做,只需添加:
- Insert text with single quotes in PostgreSQL