【问题标题】:postgres sql replace non numeric value with a constant [closed]postgres sql用常量替换非数值[关闭]
【发布时间】:2016-11-13 05:23:24
【问题描述】:

我需要从表中选择一个应该是浮动的列。但是,某些值以字符串形式出现。你有办法在 select 语句中用常量(比如 999)替换字符串吗?

谢谢

【问题讨论】:

  • 你的目的是什么?您为什么要尝试用 999 替换它?是否需要替换该列的所有值?
  • 不,我需要用 999 替换不是数字的东西
  • 好的,您确定替换为 999 不会在以后破坏您的结果吗?例如,如果您需要聚合数据并创建报告,该列是某种 ID 还是附加的,您需要在其上创建聚合和计算
  • edit你的问题添加一些示例数据和预期的输出(格式化文本请,no screenshots
  • 999 只是一个例子。我不认为这个问题太复杂。我需要的是用常量替换 select 语句中列中的每个非数值。如果您有一列的值:1,33,44,'hello',6,9,4,'whatever' 我想得到:1,33,44,999,6,9,4,999。所以像 select if_not_numeric(column,999,column) from table

标签: sql postgresql validation select


【解决方案1】:

您可以在这里找到有用的答案:https://stackoverflow.com/a/10307443/6359593。 我在这里为懒惰的人复制了代码=)

create or replace function cast_to_int(text, integer) returns integer as $$
begin
    return cast($1 as integer);
exception
    when invalid_text_representation then
        return $2;
end;
$$ language plpgsql immutable;

【讨论】:

    猜你喜欢
    • 2021-11-24
    • 2018-07-02
    • 2021-03-02
    • 1970-01-01
    • 2015-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多