如何检查 sql 数据库 table 字段为 null 或 0,如果是,则将其替换为其他列
How to check sql database table field null or 0 and if so replace it with other column
我有一个SQL查询;我想检查查询中的两列以检查它们是否为空或 0;如果是这样,那么我想用其他列的值替换 then。
这是我的查询:我已经使用 coalesce 检查它是否为空,但我如何检查 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,则应将其替换为新价格值
你可以试试:
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
表达式将零值(自然为零,或合并为零)替换为备份值。
另一种方法 - 使用 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
我有一个SQL查询;我想检查查询中的两列以检查它们是否为空或 0;如果是这样,那么我想用其他列的值替换 then。
这是我的查询:我已经使用 coalesce 检查它是否为空,但我如何检查 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,则应将其替换为新价格值
你可以试试:
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
表达式将零值(自然为零,或合并为零)替换为备份值。
另一种方法 - 使用 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