直接在列中添加换行符或回车 return 到 Postgres 中的分隔符值

Add newline or carriage return directly in a column to separator values in Postgres

我有以下查询:

SELECT id,
concat_ws(', ',
            case when isBlue then 'Blue' end,
            case when isMale then 'Male' end,
            case when isAdult then 'Adult' end) as Person1,
concat_ws(', ',
            case when isBrown then 'Brown' end,
            case when isFemale then 'Female' end,
            case when isAdult then 'Adult' end) as Person2          
from misc_table  
where id <> NULL 
order by id

这将输出以下内容

| id | Person1             | Person2
----------------------------------------------
| 1  | Blue, Male, Adult   | Brown, Female, Adult
----------------------------------------------
| 2  | Blue, Male, Adult   | Brown, Female, Adult  

但是,我希望它显示为:

| id | Person1             | Person2
----------------------------------------------
| 1  | Blue,               | Brown,
|    | Male,               | Female,
|    | Adult               | Adult 
----------------------------------------------
| 2  | Blue,               | Brown,
|    | Male,               | Female,
|    | Adult               | Adult 

似乎找不到实现此目的的简单方法。任何建议表示赞赏!

如果您使用来自 fine manual:

E'' 字符串,您可以在字符串文字中使用一些 C 风格的转义符

4.1.2.2. String Constants with C-style Escapes

PostgreSQL also accepts "escape" string constants, which are an extension to the SQL standard. An escape string constant is specified by writing the letter E (upper or lower case) just before the opening single quote, e.g., E'foo'. (When continuing an escape string constant across lines, write E only before the first opening quote.) Within an escape string, a backslash character (\) begins a C-like backslash escape sequence, in which the combination of backslash and following character(s) represent a special byte value, as shown in Table 4-1.

所以你可以说:

SELECT id,
concat_ws(E',\n', ...
-- -------^^^^^^

这会在 psql 输出中给你一些 + 标志:

| id | Person1             | Person2
----------------------------------------------
| 1  | Blue,              +| Brown,          +
|    | Male,              +| Female,         +
|    | Adult               | Adult 
...

但这只是 psql 告诉您有一个多行列值。

顺便说一句,id <> null 并不像您想象的那样,您几乎肯定想说 id is not null 以获得合理的结果。

您可以通过调用 chr:

强制换行符
SELECT id,
concat_ws(',' || CHR(10), -- HERE
            case when isBlue then 'Blue' end,
            case when isMale then 'Male' end,
            case when isAdult then 'Adult' end) as Person1,
concat_ws(',' || CHR(10), -- And HERE
            case when isBrown then 'Brown' end,
            case when isFemale then 'Female' end,
            case when isAdult then 'Adult' end) as Person2          
from misc_table  
where id IS NOT NULL -- BTW, note that nulls should be evaluated with the IS operator
order by id