SQL COALESCE()函数可以用一句话来描述: COALESCE返回为每一行传递的第一个非空值。请用一个例子,用一种简单、符合逻辑的方式重新表述这句话。
-- assume the a.id column contains the one and only NULL value in a large table
SELECT COALESCE(a.id, a.id) AS modified_id
FROM accounts a这会产生一个令人惊讶的结果,即在新列modified_id中实际创建一个值!如果函数中的第一个参数为NULL,那么第二个参数(替换第一个参数中的NULL的值)如何在结果modified_id中产生任何结果呢?我们知道第二个参数中的值必须为空,因为它确实是第一个参数。
编辑:
下面的代码在2018-08-05_20-39-19.jpg中生成结果
SELECT *
FROM accounts a
LEFT JOIN orders o
ON a.id = o.account_id
WHERE o.total IS NULL;下面的代码在2018-08-05_20-43-14.jpg中生成结果
SELECT
COALESCE(a.id, a.id) AS filled_id,
a.name, a.website, a.lat, a.long, a.primary_poc, a.sales_rep_id, o.*
FROM accounts a
LEFT JOIN orders o
ON a.id = o.account_id
WHERE o.total IS NULL;发布于 2018-08-06 12:51:13
你一定是打错了字,或者其他一些简单的原因。
这很容易验证,只需在同一查询中同时返回a.id和COALESCE(a.id, a.id)即可。确保使用别名,以便您知道您正在查看的是a.id,而不是来自其他表的id。
SELECT
a.id AS a_id,
COALESCE(a.id, a.id) AS filled_id,
a.name, a.website, a.lat, a.long, a.primary_poc, a.sales_rep_id, o.*
FROM accounts a
LEFT JOIN orders o
ON a.id = o.account_id
WHERE o.total IS NULL;发布于 2018-08-06 11:44:39
对于您提供的这个例子,如果a.id是null,那么第二个a.id当然也是null。
COALESCE对左连接很有帮助,例如
select coalesce(DE.user_id, KBU.user_id, OUD.user_id) as User_ID
LEFT JOIN dm.EDW.DIM_Employee DE
ON de.user_id = RIGHT(SubQuery.[UserID], LEN(SubQuery.[UserID]) - 5)
AND de.dss_current_flag = 'Y'
AND de.Dss_Deleted_Flag = 'N'
-- Some of the users are missing from our Dim Table so need to use other sources
LEFT JOIN tts..load_KBNetwork_Users KBU
ON KBU.UID = RIGHT(SubQuery.[UserID], LEN(SubQuery.[UserID]) - 5)
LEFT JOIN dm.dbo.organisationunitdimension OUD
ON oud.OrgUnitLevel5SourceId = RIGHT(SubQuery.[UserID], LEN(SubQuery.[UserID]) - 5)
AND oud.dss_current_flag = 'Y'如果DE为空,那么我可以从接下来的两个值中获取第一个空值(如果可能)
https://stackoverflow.com/questions/51700212
复制相似问题