Sql server sqlserver中具有空值的Pivot

Sql server sqlserver中具有空值的Pivot,sql-server,Sql Server,我的表中有这些数据 create table #school ( id int , [type] varchar(50), student bit , teacher bit, principal bit ) insert into #school ( id, [type] , student )values (1, 'Student',1) insert into #school ( id, [type] , teacher )

我的表中有这些数据

create table #school
(
  id int ,
  [type] varchar(50),
  student bit ,
  teacher bit,
  principal bit
)

 insert into #school 
 (
   id,
  [type] ,
  student 
 )values
(1, 'Student',1)

insert into #school 
(
  id,
  [type] ,
  teacher 
 )values
(1, 'Teacher',0)

 insert into #school 
(
  id,
  [type] ,
  principal  
  )values
(1, 'Principal',0)

select * from #school
如何获得以下格式的上述数据

  id   student  teacher  principal
   1     1        0       0
我尝试在sql查询中使用pivot选项,但并没有得到上面所示的结果


提前感谢。

我不明白
[type]
专栏在这里的作用是什么,也不明白您为什么认为需要重点关注

您可以使用

例如


当学生、教师为位数据类型时,“最大条件”不起作用

 select ID,
      max(case when Type = 'Student' then Student end) Car,
      max(case when Type = 'Teacher' then Teacher end) Truck,
      max(case when Type = 'Principal' then Principal end) Bicycle
    from #school
    GROUP BY ID

请考虑此结果,因为您得到了列中指定的类型:

按id从#学校组中选择id,max(学生为int)作为学生,max(教师为int))作为教师,max(校长为int))作为校长


如果需要将值作为位返回,则必须将其再次转换为位。

如果类型ie可以有多个条目,则:

SELECT 
    id,
    SUM(CAST(ISNULL(Student,0) AS INT)) AS Student,
    SUM(CAST(ISNULL(Teacher,0) AS INT)) AS Teacher, 
    SUM(CAST(ISNULL(Principal,0) AS INT)) AS Principal
FROM 
    #school 
GROUP BY 
    id
这假设您只想计算真值,否则使用前面提供的更简单的计数版本

通过使用ISNULL([fld],0),每个记录现在都有一个值,因此sum()函数现在将计算所有真实结果,因为CAST()函数将它们转换为可计数的INT数据类型

SELECT 
    id,
    SUM(CAST(ISNULL(Student,0) AS INT)) AS Student,
    SUM(CAST(ISNULL(Teacher,0) AS INT)) AS Teacher, 
    SUM(CAST(ISNULL(Principal,0) AS INT)) AS Principal
FROM 
    #school 
GROUP BY 
    id