I have a table var with some rows but only one column of type DATETIME, like this:
[Day]
2010-08-03
2010-08-04
2010-08-10
2010-08-11
I need to show on some columns but in only one row.
My result set will be limited to 5 rows, then I can limit to 5 columns too.
Example of what I need:
[Day1] [Day2] [Day3] [Day4] [Day5]
2010-08-03 2010-08-04 2010-08-10 2010-08-11 NULL
I was trying to do it using PIVOT in SQL Server 2005.
But all examples uses more columns to agregate values, then I’m not understanding.
This is the query I was trying:
SELECT r.* FROM (SELECT ROW_NUMBER() OVER (ORDER BY Day ASC) Line, Day FROM @MyDays) AS o
PIVOT (MIN(Line) FOR Day IN (Day1, Day2, Day3, Day4, Day5)) AS r
But the result is all NULL:
[Day1] [Day2] [Day3] [Day4] [Day5]
NULL NULL NULL NULL NULL
Could someone show me what I’m doing wrong?
Row_Number()just returns a number in the list 1-5 so it isn’t going to match anything in your list “Day1, Day2, Day3, Day4, Day5”. I have appended “Day” onto the front so it will.Additionally you have
MIN(Line) FOR Day IN, This needs to be the otherway around. It is the value ofDaythat you are wanting to display.