【问题标题】:Single column from Multiple columns from join in SQLSQL中连接的多列中的单列
【发布时间】:2020-09-15 08:31:13
【问题描述】:

我有一个这样的表输出,它是多个表连接的结果。

+---------+------+--------+------+
|   Id    | V1   | V2     | V3   | 
+---------+------+--------+------+
|    1    | x1   | null   |  null|
|    2    | x2   | null   |  null|
|    3    | null | x3     |  null|
|    4    | null | x4     |  null|
|    5    | null | null   |  x9  |
+---------+------+--------+------+

我想弄一张这样的桌子。

+---------+------+
|   Id    | V    |  
+---------+------+
|    1    | x1   | 
|    2    | x2   | 
|    3    | x3   |
|    4    | x4   |
|    5    | x5   |
+---------+------+

这就是我目前正在做的事情。不知道如何使三列合并为一列。

select a.identifier, a.v1, b.v2, c.v3,
from table a
full join table b on a.identifier = b.identifier
full join table c on a.identifier = c.identifier
where a.v REGEXP 'some condition'

【问题讨论】:

  • 只有v1、v2和v3?或更多列?
  • 更多栏目。为简单起见,我只添加了这些。
  • 列数是固定的吗?此外,您提供的 SQL 让我感到困惑。是一张桌子吗?如果一行同时具有 v1 和 v2 非空值怎么办?另外,您是否在合并列 v 上应用 REGEXP 条件?
  • SELECT a.identifier, COALESCE(a.v1, b.v2, c.v3) 有什么问题?
  • @Nick 将其发布为答案 :)

标签: sql join teradata


【解决方案1】:

如果每行只有一个值——或者如果你只想要第一个值——那么使用coalesce():

select id, coalesce(v1, v2, v3) as v
from t;

【讨论】:

    【解决方案2】:

    看看 - COALESCE() Function,它返回列表中的第一个非空值。

    【讨论】:

      猜你喜欢
      • 2015-07-09
      • 2011-12-01
      • 2013-05-11
      • 1970-01-01
      • 2013-07-17
      • 2010-11-12
      • 1970-01-01
      • 2021-10-15
      • 2018-05-25
      相关资源
      最近更新 更多