views:

285

answers:

1

Hi,

I have a table with data as given below:

DATE            Price
----------      ------
31/12/2009  10
31/12/2009  11
31/12/2009  12
30/12/2009  20
30/12/2009  21
30/12/2009  22
29/12/2009  30
29/12/2009  32
29/12/2009  31

I want to convert this data as given below:

31/12/2009  30/12/2009  29/12/2009
----------  ----------  ----------
10          10          10
11          11          11
12          12          12

But the values in the date column is dynamic. So, I dont know how to use this using SQL Server Pivot.

Could you please let me know how to get this data.

Given below is the script to replicate this scenario:

CREATE TABLE TEMP(EffectiveDate DATETIME,Price INT)
INSERT INTO TEMP(EffectiveDate,Price)
SELECT GETDATE(),10
UNION ALL
SELECT GETDATE(),11
UNION ALL
SELECT GETDATE(),12
UNION ALL
SELECT GETDATE()-1,20
UNION ALL
SELECT GETDATE()-1,21
UNION ALL
SELECT GETDATE()-1,22
UNION ALL
SELECT GETDATE()-2,30
UNION ALL
SELECT GETDATE()-2,32
UNION ALL
SELECT GETDATE()-2,31

SELECT CONVERT(VARCHAR,EffectiveDATE,103) AS 'DATE',Price FROM Temp

Thanks in advance,

Mahesh

+2  A: 

OK, as I mentioned, your data does not make sense, but maybe this can help.

The only way to create a dynamic pivot, is by creating dynamic sql.

Also, PIVOT requires that you use an Aggregate function (SUM, AVG, COUNT).

Ok, let see if this can help you.

CREATE TABLE #TEMP  (EffectiveDate DATETIME,Price INT) 
INSERT INTO #TEMP(EffectiveDate,Price) 
SELECT GETDATE(),10 
UNION ALL 
SELECT GETDATE(),11 
UNION ALL 
SELECT GETDATE(),12 
UNION ALL 
SELECT GETDATE()-1,20 
UNION ALL 
SELECT GETDATE()-1,21 
UNION ALL 
SELECT GETDATE()-1,22 
UNION ALL 
SELECT GETDATE()-2,30 
UNION ALL 
SELECT GETDATE()-2,32 
UNION ALL 
SELECT GETDATE()-2,31 

DECLARE @Cols VARCHAR(MAX)
SELECT @cols = COALESCE(@cols + ',[' + colName + ']',
                         '[' + colName + ']')
FROM    (
            SELECT DISTINCT 
                    CONVERT(VARCHAR,EffectiveDATE,103) colName
            FROM    #TEMP
        ) s
ORDER BY colName DESC

DECLARE @query VARCHAR(MAX)
SET @query = N'SELECT *
FROM
(SELECT CONVERT(VARCHAR,EffectiveDATE,103) AS ''DATE'',Price
            FROM    #TEMP) p
PIVOT
(
SUM(Price) FOR DATE IN
( '+
@cols +' )
) AS pvt' 

EXECUTE(@query)


DROP TABLE #TEMP
astander
It worked. Thanks a lot.
Mahesh