首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何检查sql数据库表字段为null或0,如果是,则替换为其他列

如何检查sql数据库表字段为null或0,如果是,则替换为其他列
EN

Stack Overflow用户
提问于 2020-05-07 14:52:14
回答 2查看 79关注 0票数 0

我有一个SQL查询;我想检查查询中的两个列,看看它们是null还是0;如果是,那么我想用其他列的值替换它们。

下面是我的查询:我使用coalesce检查它是否为null,但是如何检查0,以及如何用其他值替换列?

代码语言:javascript
运行
复制
SELECT 
    t.Name
    ,t.Code
    ,c.Description
    ,st.APriceOld
    ,st.CPriceOld
    ,st.APriceNew
    ,st.CPriceNew
    COALESCE(st.APriceOld,st.APriceNew),
    COALESCE(st.CPriceOld,st.CPriceNew) 
FROM
    Table t
INNER JOIN
    STCP st ON st.PriceId = t.PriceId

有没有人能帮我得到预期的结果?

因此,如果旧的价格值为0或null,则应将其替换为新的价格值

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-05-07 15:23:21

另一种方法-使用nullif()函数:

代码语言:javascript
运行
复制
SELECT 
    t.Name
    ,t.Code
    ,c.Description
    ,st.APriceOld
    ,st.CPriceOld
    ,st.APriceNew
    ,st.CPriceNew
    COALESCE(NULLIF(st.APriceOld, 0), st.APriceNew),
    COALESCE(NULLIF(st.CPriceOld, 0), st.CPriceNew) 
FROM
    Table t
INNER JOIN
    STCP st ON st.PriceId = t.PriceId
票数 2
EN

Stack Overflow用户

发布于 2020-05-07 14:56:49

您可以尝试:

代码语言:javascript
运行
复制
SELECT
    t.Name,
    t.Code,
    c.Description,
    st.APriceOld,
    st.CPriceOld,
    st.APriceNew,
    st.CPriceNew,
    CASE WHEN COALESCE(st.APriceOld, 0) <> 0
         THEN st.APriceOld ELSE st.APriceNew END AS APrice,
    CASE WHEN COALESCE(st.CPriceOld, 0) <> 0
         THEN st.CPriceOld ELSE st.CPriceNew END AS CPrice
FROM Table t
INNER JOIN STCP st ON st.PriceId = t.PriceId;

这里的逻辑是首先使用COALESCE有条件地将NULL旧价格值替换为零。然后,我们使用CASE表达式将零值(自然为零或已合并为零)替换为备份值。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61651578

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档