Name columns with value returned from Select

Asked

Viewed 307 times

1

I am trying to rename SELECT column with the value returned from another SELECT.

Ex:

SELECT ID, NOME, QUANTIDADE AS QTDE_4 FROM TESTE

Where in QTDE_4, 4 would be the current month. I tried to put the value of the separate query in a variable, but without success too.

My query was getting like this:

SELECT ID, NOME, QUANTIDADE AS CONCAT(`QTD_`, '', SELECT MONTH(NOW()) ) FROM TESTE

The database I’m using is MYSQL. If anyone knows how to help, pls comments.

  • Why do you want to do this?

  • Guy if you put the name of the dynamic column in SELECT as you will to get it in the result set?

  • Alias is a constant. To create aliases dynamically, you will have to mount your query as a string and then execute it. But, what is your real purpose? Your sample query does not justify this approach.

  • The idea was to cross-check with another table and take the amount of transactions that occurred in the last 3 months, but to find out what months these transactions were, I wanted to rename the column with each month.

  • It’s silly to do so, if you put an example of the data of your tables as example and structure of them and show the result final you want we can suggest more timely solutions to your problem

1 answer

1

declare @sql varchar(300) 

select @nome = 'QTD_' + cast ( MONTH(getdate()) as varchar) 

print @nome 

select @sql = 'select id, nome ' + @nome + ' from bot_arquivo '

print @sql

exec(@sql)

I confess to not seeing reason for this use despite the scenario you commented. I advise to review if this solution is really the best way to use SQL.

Browser other questions tagged

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