使用数据透视表将行转换为列

时间:2019-10-24 18:07:34

标签: c# sql sql-server pivot

我打算将此表的行变成列。

这是我的桌子:

 select  tipoDocumento_id,nome,resultado
  from Campos

tipoDocumento_id nome                           resultado
---------------- ------------------------------ ------------------------------
62               Data:                          2019-05-20                    
62               N.I.F. fornecedor:             501062327                     
62               Total:                         31,14                         
62               Número fatura:                 FT19/04006                    
63               Data:                          2019-05-23                    
63               N.I.F. fornecedor:             501062327                     
63               Total:                         39,14                         
63               Número fatura:                 FT19/04007

现在我有这个查询,但是它返回NULL

select Data,NIF , Total, Numero fatura
from
(
  select  tipoDocumento_id,nome,resultado
  from Campos
) d
pivot
(
  max(tipoDocumento_id)
  for resultado in (Data,NIF , Total, Numero fatura)
) piv;

我的坏处可能是与max()

聚合

我想要这样的结果

ID    Data:          N.I.F. fornecedor:    Total:      Número fatura:
62    2019-05-20     501062327             31,14       FT19/04006
63    2019-05-23     501062327             39,14       FT19/04007

有人可以给我一点帮助吗?

2 个答案:

答案 0 :(得分:1)

你在盘旋

select *
from
(
  select id=tipoDocumento_id
        ,nome
        ,resultado
  from Campos
) d
pivot
(
  max(resultado)
  for nome in ([Data:],[N.I.F. fornecedor:],[Total:],[Número fatura:])
) piv;

答案 1 :(得分:0)

这就是我在谈论使用case语句而不是数据透视表(不是在寻找改变答案的方法,只是提供另一个选择):

 select  tipoDocumento_id
     ,max(case when nome = 'Data:' then resultado else null end) as [Data:]          
     ,max(case when nome = 'N.I.F. fornecedor:' then resultado else null end) as [N.I.F. fornecedor:]
     ,max(case when nome = 'Total:' then resultado else null end) as [Total:]
     ,max(case when nome ='Número fatura:' then resultado else null end) as [Número fatura:]
  from Campos
group by tipoDocumento_id
相关问题