SQL 服务器中 table 没有数据时显示空值

Display empty value when there is no data on the table in SQL Server

我有 table 并像这样从行到列查询 select 数据:

 id  |  type    | data
-----------------------
  1  |  Name    | John
  1  |  Gender  | Male
  1  |  Code    | 1782
  2  |  Name    | Dave
  2  |  Gender  | Male

查询:

select a.id, a.data as [Name], b.data as [Gender], c.data as [Code]
from table1 a join table1 b on a.id = b.id
              join table1 c on b.id = c.id
where a.type = 'Name' and b.type = 'Gender' and c.type = 'Code'

结果:

  id |  Name   | Gender | Code  
 ------------------------------
  1  |  John   |  Male  | 1782

在这种情况下,名称为 'Dave' 的 ID 编号 2 没有 'Code',因此它不会出现在结果中。我如何仍然在 'Code' table 上显示带有空数据或 NULL 的结果,所以它会得到这样的结果:

  id |  Name   | Gender | Code  
 ------------------------------
  1  |  John   |  Male  | 1782 
  2  |  Dave   |  Male  |
select a.id, a.data as [Name], b.data as [Gender], c.data as [Code]
from table1 a
left join table1 b on a.id = b.id and b.type='Gender'
left join table1 c on b.id = c.id and c.type='Code'
where a.type = 'Name' 

使用 pivot 查询

select *
from   table1
       pivot
       (
           max(data)
           for type in ([Name], [Gender], [Code])
       ) p

demo

您可以使用 CASE 表达式代替 JOINs :

SELECT
  a.id,
  MAX(CASE WHEN a.type = 'Name' THEN a.data ELSE '' END) AS [Name],
  MAX(CASE WHEN a.type = 'Gender' THEN a.data ELSE '' END) AS [Gender],
  MAX(CASE WHEN a.type = 'Code' THEN a.data ELSE '' END) AS [Code]
FROM table1 a
WHERE
    a.type IN('Name', 'Gender', 'Code')
GROUP BY a.id