我有一个SQL查询;我想检查查询中的两个列,看看它们是null还是0;如果是,那么我想用其他列的值替换它们。
下面是我的查询:我使用coalesce检查它是否为null,但是如何检查0,以及如何用其他值替换列?
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,则应将其替换为新的价格值
发布于 2020-05-07 15:23:21
另一种方法-使用nullif()函数:
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发布于 2020-05-07 14:56:49
您可以尝试:
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表达式将零值(自然为零或已合并为零)替换为备份值。
https://stackoverflow.com/questions/61651578
复制相似问题