Difficulty in dynamizing columns in MSSQL

Asked

Viewed 25 times

0

Gentlemen, good morning !

I’m having a little trouble building this query in Microsoft SQL 2019

Could someone maybe give me a light ?

I have a base like this

Codfuncionario | cod_centro_custo | perc_rateio

 1         |       1          |    50%
 1         |       2          |    50%
 2         |       1          |    100%

And I need to dynamically transform it:

codFunctioning | cod_centro_custo_1 | perc_valor1 | cod_centro_custo2 | perc_valor2 ..

 1         |        1           |    50%      |       2           |    50%
 2         |        1           |    100%     |     NULL          |    NULL
  • 1

    and what have we already done? ask your current query and where are you struggling

  • Search by PIVOT , https://docs.microsoft.com/pt-br/sql/t-sql/queries/from-using-pivot-and-unpivot?view=sql-server-ver15

1 answer

0

I was going to the pivot path, but it’s not necessarily what I need, because I want the cost center fields that are in the columns to be in rows.

I was using this query, but it generates only the header with the cost center text in this way

inserir a descrição da imagem aqui

declare @colunas_pivot as nvarchar(max) ,@command_sql as nvarchar(max)

SET @colunas_pivot = Stuff( SELECT DISTINCT ',' + quotename(CODCENCUS) -, ',' + quotename('value') FROM TFPRTF FOR XML PATH (') ), 1, 1, '') print @colunas_pivot set @commandndo_sql = ' select * from ( SELECT CODFUNC , ,SUM(APPORTIONMENT) APPORTIONMENT FROM TFPRTF GROUP BY
CODFUNC , ) inline pivot ( sum(PERCRATEIO) for CODCENCUS in (' + @colunas_pivot + ')) in_columns order by 1' print @comando_sql execute(@command sql) go

And I need you to stay that way :

inserir a descrição da imagem aqui

  • The bad point of the pivot is that what will be 'colunado' needs to be known and named , but seems to me to be case of pivot yes. Sometimes (Oracle) I do PIVOT by CASE , may be the case , but it also falls into the problems of columns having to be known.

Browser other questions tagged

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