1
I have a table which I turn rows into columns with PIVOT. 'Chumbando' the name of the columns, works very well, however I will need to do this dynamically. There is the possibility to use variables to define the column names?
SELECT PRODUTO,
ISNULL([@MES3],0) AS MES3,
ISNULL([@MES2],0) AS MES2,
ISNULL([@MES1],0) AS MES1,
ISNULL([@MES0],0) AS MESATUAL
FROM #VENDASESTM
PIVOT (SUM(QTDVEND) FOR EMISSAO IN ([@MES3],[@MES2],[@MES1],[@MES0]) )P
ORDER BY PRODUTO
These four months are dynamic and informed in the Store Procedure call. SP creates the #VENDASESTM table correctly with products, chosen months and quantities sold. Then I need to transform it with PIVOT also dynamically.
The way it is above, the result was 0 in all columns. I did the conference and there are sales, so something is wrong.
If you do select by changing the month variables (exe; @MES3), for a fixed value (exe; 3) it works ?
– Marco Souza
Yes @Marconcíliosouza [05],[06],[07] and chumbados etc works perfectly. But now I need the columns to be determined by variable return
– Caio César Henrique
Which database and type of ISSUE column :?
– Marco Souza
SQL Database and ISSUANCE as Character 2
– Caio César Henrique
SQL, is not database, your Character 2 you speak varchar(2)? the database is sql server?
– Marco Souza
I just forgot the rest of the SQL name, rs. SQL SERVER 2008 I just switched to Varchar(2) to do a test, before I was just like Char... is processing the query (it’s kind of heavy and the server is slow). Let’s see the result.
– Caio César Henrique
Gave anyway, returned everything zeroed
– Caio César Henrique
your @MES3 parameter is also of the same type?
– Marco Souza
Yes, the four months are the same
– Caio César Henrique