How to transpose rows into columns?

Asked

Viewed 1,696 times

0

It’s already been answered by Motta, thank you for your patience.

How can I transpose rows to columns in Sqlserver, so something like that:

inserir a descrição da imagem aqui

Stick to this format?

inserir a descrição da imagem aqui

  • 1

    Comrade, make your question clearer, explain what you need, because you can’t understand what you really want

  • 1

    Have you searched about pivot table? would that be what you want?

  • John, put in your question you want to know how to transform the result of the query that is in columns in rows.

3 answers

5

A slightly more elegant form than was presented, would be to use unpivot,

select *
from Tabela
unpivot
(
  Valor
  for Ano in ([Jan], [Fev], [Mar], [Abr], [Mai], [Jun], [Jul], [Dez]) unpiv
order by ano desc

4


With UNION maybe

select 'jan' , jan linhabase from tabela 
union
select 'fev' , fev linhabase from tabela 
union
...
select 'dez' , dezlinhabase from tabela 

But the problem became unclear to me , another thing is what seems to me a bad model.

Also search by UNPIVOT

  • That’s just what I needed, thank you Motta!

0

If you want to count the values. Use the SUM Example..

SELECT sum(Jan), count(Fev), sum(Mar),..... FROM tabela.

Result will be the sum of the rows in the columns in January, February, etc...

  • Do not count, it is pq I took from a table fake the second image, but it is to pass the values from row to column, instead of 12 rows make 2 columns, one month pro and another for the values of the months

  • 1

    As the gentleman above said, further specify your question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.