【问题标题】:Retrieve data from the same column in two columns从两列中的同一列检索数据
【发布时间】:2019-01-09 13:54:20
【问题描述】:

我在 PostgreSQL 中有一个表,如下所示:

ID      NAME
450     China
525     Germany
658     Austria

我想同时查询 ID 500 的每个名称,并使用

在两列中检索结果
array_to_string(array_agg(NAME),  ',  '). 

我需要以下结果:

column1 (ID < 500)      column2 (ID > 500)
China                   Germany, Austria

【问题讨论】:

  • 你使用的是哪个 Postgres 版本(select version(); 会告诉你)

标签: postgresql


【解决方案1】:

尝试使用条件聚合:

SELECT
    STRING_AGG(CASE WHEN ID < 500 THEN NAME END, ', ')  AS ID_lt_500,
    STRING_AGG(CASE WHEN ID >= 500 THEN NAME END, ', ') AS ID_gt_500
FROM yourTable;

Demo

编辑:

如果您使用的 Postgres 版本不支持 STRING_AGG,则照常执行:

SELECT
    ARRAY_TO_STRING(ARRAY_AGG(CASE WHEN ID < 500 THEN NAME END), ', ')  AS ID_lt_500,
    ARRAY_TO_STRING(ARRAY_AGG(CASE WHEN ID >= 500 THEN NAME END), ', ')  AS ID_gt_500
FROM yourTable;

Demo

【讨论】:

  • 我使用的是旧版本,string_agg 函数对我不起作用。我尝试了以下,2列存在,但聚合函数不起作用。 array_to_string(array_agg(CASE WHEN ID = 500 THEN NAME END), ', ') AS ID_gt_500 怎么了?
  • 谢谢蒂姆,但现在它在过滤器处或附近显示语法错误。我不知道怎么了...
  • @user6265779 您的 Postgres 版本似乎不支持 STRING_AGGFILTER。我又更新了答案。
【解决方案2】:

类似:

select (select string_agg(name, ', ') 
        from the_table
        where id <= 500) as column1, 
       (select string_agg(name, ', ') 
        from the_table
        where id > 500) as column2;

或者:

select string_agg(name, ', ') filter (where id <= 500) as column1, 
       string_agg(name, ', ') filter (where id > 500) as column2
from the_table;

【讨论】:

  • @TimBiegeleisen:Oxford Dictionary 不这么认为。
  • @KaushikNayak 我的立场是正确的。不过,它并没有出现在韦氏词典中,我也从未在写作中使用过它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多