Convert line into columns using pivot

Viewed 71

I aim to turn rows of this table into columns.

This is my table:

 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

For now I have this query but it's returning 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;

Probably my bad it´s on aggregating with max()

I want a result like that

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

Can someone give me a little help?

2 Answers

You were circling around it

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;

This is what I was talking about with using a case statement instead of pivot (not looking for you to change answer, just giving another option):

 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
Related