需要在单独的行中将NULL显示为缺少属性的值

问题描述

我在MSsql 17中有一个表,如下所示:

Attribute   Value   Code
Country     Canada  AA
Source      EFT     AA
Manager     Ahmad   AA
Source      EFT     BB
Manager     Mike    BB
Country     Brazil  CC
Source      Cash    CC

我需要所有代码具有相同的行数,并显示相同的属性,如果表中不存在该值,则应为NULL。我正在寻找的输出

Attribute   Value   Code
Country     Canada  AA
Source      EFT     AA
Manager     Ahmad   AA
Country     NULL    BB
Source      EFT     BB
Manager     Mike    BB
Country     Brazil  CC
Source      Cash    CC
Manager     NULL    CC

能帮我吗?感激!

解决方法

使用cross join生成行,然后使用left join引入现有值:

select a.attribute,t.value,c.code
from (select distinct code from t) c cross join
     (select distinct attribute from t) a left join
     t
     on c.code = t.code and a.attribute = t.attribute