如何在 sql 的 unpivot 中进行 NULL 检查

how to do a NULL check in unpivot in sql

我在 sql 服务器上使用以下 sql 查询。

select distinct  [Value],Label,Id from(
select distinct [Name], Code, I as Id,I + ':' + [Value] as label, [Value]
from [test].[dbo].[emp]
unpivot
(
  [Value]
  for I in (product, model)
) as dataTable) as t

我想要的是,如果 unpivot 语句中的任何 [Value] 为空,它应该 return 'unknown' 到嵌套的 select 语句。

如何实现?

更新--

//this is wrong sql. Just want to show what is required
select distinct  [Value],Label,Id from(
select distinct [Name], Code, coalesce(I as Id,'unknown'),coalesce(I,'unknown') + ':' + [Value] as label, coalesce([Value],'unknown')
from [test].[dbo].[emp]
unpivot
(
  [Value]
  for I in (product, model)
) as dataTable) as t

您似乎在寻找 coalesce():

from (select distinct [Name], Code, I as Id,
             I + ':' + coalesce([Value], 'unknown') as label,
            [Value]
      from [test].[dbo].[emp]
     ) e

我建议将查询写成:

我不确定你真正想要什么,但我建议使用 apply.

编写查询
select distinct v.id, (v.id + ':' + coalesce(v.[Value], 'unknown')) as label,
       coalesce(v.[Value], 'unknown') as value
from [test].[dbo].[emp] e cross apply
     (values (e.product, 'product'), (e.model, 'model')
     ) v(value, id);

这看起来更简单,而且性能可能也更好。