1

I've got an issue generating an alias for a field in a query which for example gives me the revenue from last year and the year before. I was in the understanding that I could do something like :

SELECT 
    1234 AS 'REVENUE' + CAST (year(DATEADD(year,-1,getdate())) AS VARCHAR(20))
    4321 AS 'REVENUE' + CAST (year(DATEADD(year,-2,getdate())) AS VARCHAR(20))

But this doesn't work. Does somebody know how to get this done?

I want to end up with a table like

rownr|revenue2014|revenue2013
-----------------------------
1    |1234       |4321

Thanks a lot in advance!

greets Niels

7
  • do you want the column name as revenue Commented Apr 8, 2015 at 9:20
  • no I just want it to say for example "REVENUE2014" and want that column to say "REVENUE2015" next year. Commented Apr 8, 2015 at 9:23
  • please give expected output in your question Commented Apr 8, 2015 at 9:23
  • 2
    I think you have to use dynamic sql to achieve what you want, unless you can solve your original problem in some other way Commented Apr 8, 2015 at 9:26
  • 1
    Also, if this is being fed into something else (almost all queries are) such as a reporting tool or an application, performing the renaming there may be much easier than trying to do it in the SQL. Commented Apr 8, 2015 at 9:32

1 Answer 1

6
DECLARE @sql VARCHAR(1000);
SET @sql = 'SELECT 
    1234 AS REVENUE' + CAST (year(DATEADD(year,-1,getdate())) AS VARCHAR(20)) + ',
    4321 AS REVENUE' + CAST (year(DATEADD(year,-2,getdate())) AS VARCHAR(20))
PRINT @sql
EXEC (@sql)

It is impossible to do that in the static SQL query. So only this way.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Dmitrij , can I write dynamics SQL in Views , I want to have dynamics alias in my View , because my views are used by thereporter.
no, you can't have dynamic views. Usually report tools themselves can pivot data, so you can implement that logic there

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.