我有以下查询:
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
似乎无法找到实现此目的的简单方法。任何建议都表示赞赏!
答案 0 :(得分:6)
如果您使用fine manual中的E''
字符串,则可以在字符串文字中使用一些C风格的转义符:
<强> 4.1.2.2。具有C风格转义的字符串常量
PostgreSQL还接受“转义”字符串常量,它是SQL标准的扩展。通过在开始单引号之前写入字母
E
(大写或小写)来指定转义字符串常量,例如E'foo'
。 (当跨越行继续转义字符串常量时,仅在第一个开始引号之前写入E.)在转义字符串中,反斜杠字符(\
)开始类似C的反斜杠转义序列,其中反斜杠和后续字符的组合表示一个特殊的字节值,如表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
以获得明智的结果。
答案 1 :(得分:2)
您可以通过调用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