Question : Change rows to columns specifically in sql 2005

Hai,
Take a look at my query result ...
Date Value
d1    1.1
d1     2.7
d1    3.1
d2    4.6
d2    2.2

.... Here d1, d2 are date fields and value is double

My query goes like this


SELECT  T.DURATION AS VALUE ,(DATEADD(D, 0, DATEDIFF(D, 0, START_DATETIME))) AS DATE,START_DATETIME from [TRAINING-SESSION] AS T JOIN [SCHEDULE-ACT] AS S
            ON T.I_SCHEDULE_ACT = S.I_SCHEDULE_ACT
            START_DATETIME between @pistartdate and @pienddate

But The result i want is of the form

d1  1.1  2.7  3.1
d2  4.6  2.2  

This means those values with similar dates are grouped to become
one row...
How could i achieve this ... Thanks In advance... Am a newcomer to
this site.. and am running out of points So am awarding lesser points
eventhough i know its worth more....            

Answer : Change rows to columns specifically in sql 2005

urvinayan, sm394 gave an example of putting together dynamic SQL statement which from what I glanced has all the concepts I was meaning in my comment, so that should help you understand what I mean there.  In my original code, I forgot to add the alias for the derived table:

SELECT *
FROM (
SELECT  T.DURATION AS [VALUE]
, row_number() OVER (PARTITION BY DATEADD(D, 0, DATEDIFF(D, 0, START_DATETIME)) ORDER BY START_DATETIME) AS RowNumber
, DATEADD(D, 0, DATEDIFF(D, 0, START_DATETIME)) AS [DATE]
FROM [TRAINING-SESSION] AS T JOIN [SCHEDULE-ACT] AS S
ON T.I_SCHEDULE_ACT = S.I_SCHEDULE_ACT
WHERE START_DATETIME between @pistartdate and @pienddate
) derived
PIVOT (SUM([VALUE]) FOR RowNumber IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) p


To further help the solution, if you can break this appart and have a VIEW that would work much easier for you.

You could take the whole derived table code and put in a view.

i.e. vw_DurationByDateOrdered
SELECT  T.DURATION AS [VALUE]
, row_number() OVER (PARTITION BY DATEADD(D, 0, DATEDIFF(D, 0, START_DATETIME)) ORDER BY START_DATETIME) AS RowNumber
, DATEADD(D, 0, DATEDIFF(D, 0, START_DATETIME)) AS [DATE]
FROM [TRAINING-SESSION] AS T JOIN [SCHEDULE-ACT] AS S
ON T.I_SCHEDULE_ACT = S.I_SCHEDULE_ACT
WHERE START_DATETIME between @pistartdate and @pienddate

Then in your dynamic sql creation, you could --
SELECT MAX(RowNumber)  FROM vw_DurationByDateOrdered;

And then in a loop from 1 - max, create a string of the row number values as shown in sm394's link.

Hope that helps.

Regards,
Kevin
Random Solutions  
 
programming4us programming4us