在sqlserver中使用空值进行透视

时间:2014-10-22 12:37:16

标签: 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 
 )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选项,但我没有得到上面的内容

提前致谢。

4 个答案:

答案 0 :(得分:1)

如果某个类型可以有多个条目,即。然后:

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

这假设你只想计算TRUE值,否则使用前面提供的更简单的计数版本。

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

答案 1 :(得分:0)

我不知道[type]列在此处的用途是什么,或者您认为需要转动的原因

您可以使用GROUP BY

实现上述目标

E.g。

SELECT id, COUNT(student) as student, COUNT(teacher) as teacher, COUNT(principal) as principal
GROUP BY id

答案 2 :(得分:0)

当学生,教师是位数据类型

时,MAX条件不起作用
 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

答案 3 :(得分:0)

请考虑此结果,因为您已在列中指定了类型:

选择id,max(cast(student as int))作为student,max(cast(teacher as int))作为教师,max(cast(principal as int))作为校长来自#school group by id

如果你需要返回值,则必须再次将它们转换为位。