在Redshift中合并多行非空值

时间:2016-06-02 17:16:07

标签: postgresql amazon-redshift

我想获得一行只包含表格中的非空值,可以从以下代码中复制:

select
  1 as unique_id,
  'null' as first,
  'second' as second,
  'null' as third
union all
select
  1 as unique_id,
  'first' as first,
  'null' as second,
  'null' as third
union all
select
  1 as unique_id,
  'null' as first,
  'null' as second,
  'third' as third

1 个答案:

答案 0 :(得分:0)

提供的代码的输出(假设'null'应为NULL)是:

1, 'first', NULL, NULL
1, NULL, 'second', NULL
1, NULL, NULL, 'third'

通过'merge',我假设你想要输出看起来像:

1, 'first', 'second', 'third'

这可以通过以下方式完成:

SELECT MAX(first), MAX(second), MAX(third) FROM ... GROUP BY unique_id

当然,这假设您每个unique_id只出现一次值。您可以类似地使用其他函数,例如MINLISTAGG - 它们只需要排除NULL值。