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

Sir*_*its 4 sql string postgresql

我有以下查询:

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
Run Code Online (Sandbox Code Playgroud)

哪个会输出以下内容

| id | Person1             | Person2
----------------------------------------------
| 1  | Blue, Male, Adult   | Brown, Female, Adult
----------------------------------------------
| 2  | Blue, Male, Adult   | Brown, Female, Adult  
Run Code Online (Sandbox Code Playgroud)

但是,我宁愿让它显示为:

| id | Person1             | Person2
----------------------------------------------
| 1  | Blue,               | Brown,
|    | Male,               | Female,
|    | Adult               | Adult 
----------------------------------------------
| 2  | Blue,               | Brown,
|    | Male,               | Female,
|    | Adult               | Adult 
Run Code Online (Sandbox Code Playgroud)

似乎无法找到实现这一目标的简单方法.任何建议表示赞赏!

mu *_*ort 7

如果使用E''字符串,可以在字符串文字中使用一些C风格的转义符,来自精细的手册:

4.1.2.2.具有C风格转义的字符串常量

PostgreSQL还接受"转义"字符串常量,它是SQL标准的扩展.通过E在开始单引号之前写入字母(大写或小写)来指定转义字符串常量,例如E'foo'.(当在行之间继续转义字符串常量时,仅在第一个开始引号之前写入E.)在转义字符串中,反斜杠字符(\)开始一个类似C的反斜杠转义序列,其中反斜杠和后续字符的组合(s )表示一个特殊的字节值,如表4-1所示.

所以你可以说:

SELECT id,
concat_ws(E',\n', ...
-- -------^^^^^^
Run Code Online (Sandbox Code Playgroud)

这会+在psql输出中给你一些迹象:

| id | Person1             | Person2
----------------------------------------------
| 1  | Blue,              +| Brown,          +
|    | Male,              +| Female,         +
|    | Adult               | Adult 
...
Run Code Online (Sandbox Code Playgroud)

但这只是psql告诉你有一个多行列值.

顺便说一句,id <> null没有做你认为它做的事,你几乎肯定想说id is not null要获得明智的结果.


Mur*_*nik 5

您可以通过调用强制换行符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
Run Code Online (Sandbox Code Playgroud)