【问题标题】:how to combine two columns of integer in PostgreSQL?如何在 PostgreSQL 中合并两列整数?
【发布时间】:2018-01-23 05:38:52
【问题描述】:

我有以下查询:

select col1, col2
from ...
where...

给出:

col1  col2
5
       17
4       5
12
5
       20
4      17
2       3

我想将其转换为没有重复的一列,如下所示:

col3
5
17
4
12
20
2
3

我该怎么做? 我读过这个话题Combine two columns and add into one new column,但这不是我需要的……运营商||在这里帮不上忙。

编辑: col3 只是出现在 col2col1 中的所有数字的列表。

【问题讨论】:

  • 第三行有 4 个,而不是 5 个 - 为什么?如果两者都指定,是否有使用第一列的规则?.. 尝试select coalesce(col1,col2) from table - 它将使用 col1,如果 col1 为空,则 col2
  • @VaoTsun 逻辑是向我显示出现在任何列中但没有重复的所有数字。 col3 只是出现在 col2 和 col1 中的所有数字的列表。

标签: sql postgresql


【解决方案1】:

col3 只是出现在 col2 和 col1 中的所有数字的列表。

在这种情况下,这可能就是您要查找的内容:

SELECT col1
FROM ...
WHERE ...
UNION
SELECT col2
FROM ...
WHERE ...

【讨论】:

    【解决方案2】:

    看来你需要union

    select col1 as col3 from t where col1 is not null
    union
    select col2 as col3 from t where col2 is not null
    

    【讨论】:

      【解决方案3】:

      您可以使用https://www.postgresql.org/docs/current/static/functions-conditional.html#FUNCTIONS-COALESCE-NVL-IFNULL 中记录的 COALESCE 函数;它返回第一个不为空的参数:

      yesql# select col1, col2, coalesce(col1, col2) from foo;
       col1 │ col2 │ coalesce 
      ══════╪══════╪══════════
          5 │    ¤ │        5
          ¤ │   17 │       17
          4 │    5 │        4
         12 │    ¤ │       12
          5 │    ¤ │        5
          ¤ │   20 │       20
          4 │   17 │        4
      (7 rows)
      

      【讨论】:

        【解决方案4】:
        select coalesce(col1,col2) 
        from table 
        

        它将使用col1,如果col1为null,则col2

        https://www.postgresql.org/docs/current/static/functions-conditional.html#FUNCTIONS-COALESCE-NVL-IFNULL

        COALESCE 函数返回它的第一个参数,它不是 空值。只有当所有参数都为 null 时才返回 Null。它经常 用于在数据为空值时用默认值替换 检索显示

        【讨论】:

        • coalesce 是不够的......我编辑了我的例子来说明原因。数字 3 永远不会出现在使用 coalesce 的最终结果中。
        • 在您的样本中 20.....2, 3 缺少 4, 17 - 是因为您只想要不同的值吗?我回答认为您想合并两列,而不仅仅是选择两列作为一个
        猜你喜欢
        • 1970-01-01
        • 2012-12-13
        • 1970-01-01
        • 1970-01-01
        • 2022-11-10
        • 2015-09-04
        • 1970-01-01
        • 1970-01-01
        • 2023-01-23
        相关资源
        最近更新 更多