Click here to Skip to main content
15,881,898 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
SQL
Declare @year1 varchar(10)='1998'
Declare @year2 varchar(10)='1999'

select
     sum(case when year=@year1 then sales end) '1998'--@year1
    ,sum(case when year=@year2 then sales end) '1999'--@year2
from salestable

In the above query instead of giving static column names i wanna pass the variable value as a column alias name in case.
If i pass 2004 for variable means in want to get 2004 as a column name...
Posted
Updated 16-Sep-13 23:36pm
v2
Comments
Abdul Quader Mamun 17-Sep-13 5:37am    
You need to use dynamic SQL.

To convert rows as columns, use PIVOT[^], instead doing it with CASE WHEN ... END statement.

SQL
DECLARE @cols VARCHAR(300)
DECLARE @dt VARCHAR(2000)
DECLARE @pt VARCHAR(4000)

SET @cols = '[1998],[1999],[2000]'

SET @dt = 'SELECT ProductID, YEAR(SalesDate) AS [Year], Sales FROM ProductSales'

SET @pt = 'SELECT ProductID, ' + @cols + ' ' +
          'FROM (' + @dt + ') AS DT ' +
          'PIVOT(SUM(Sales) FOR [Year] IN(' + @cols + ')) AS PT'
EXEC(@pt)


For further information, please see:
http://blog.sqlauthority.com/2008/06/07/sql-server-pivot-and-unpivot-table-examples/[^]
Simple Way To Use Pivot In SQL Query[^]
How to Perform Pivot Operation in T-SQL..?[^]
 
Share this answer
 
v2
Comments
Raja Sekhar S 18-Sep-13 0:17am    
Nice.. Forgot about Pivot... +5!
Maciej Los 18-Sep-13 14:56pm    
Thank you ;)
try

sum(case when year=@year1 then sales as @year1 end)
 
Share this answer
 
SQL
Declare @year1 varchar(10)='1998'
Declare @year2 varchar(10)='1999', @Sql nvarchar(200)

Set @Sql ='Select sum(case when year=' + @year1 +' then sales end) [' + @year1 +'],sum(case when year=' + @year2 + ' then sales end) [' + @year2 +'] from salestable'

-- Sql Data will be
-- Select sum(case when year=1998 then sales end) [1998],
--        sum(case when year=1999 then sales end) [1999] 
-- from salestable

Exec (@Sql)
 
Share this answer
 
v4
Comments
Raju9959 17-Sep-13 7:26am    
is it any possibility to get such thing without dynamic statements
Raja Sekhar S 17-Sep-13 7:31am    
I think it's not possible.... any one correct me if am wrong...
is there any reason for you to not use dynamic Query..?
Raju9959 17-Sep-13 7:37am    
Not like that i want to know the alternative method if available...
Raja Sekhar S 17-Sep-13 7:42am    
No other way as of i know... if it answered your question mark it as answer...
Maciej Los 17-Sep-13 7:58am    
See my answer.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900