开发者

SQl rows to columns conversion

I have a table ClassAttendance and I'm using MSSQL 2005

studentID    attendanceDate    status
-------------------------------------
*1004          2010-03-17        0
 1005          2010-03-17        1
 1006          2010-03-17        0
 1007          2010-03-17        0
*1004          2010-03-19        0
 1005          2010-03-19        1
 1006          2010-03-19        0
 1007          2010-03-19        0
*1004      开发者_开发知识库    2010-03-20        1

as you can see studentID is a foreign Key for a table called StudentData and attendedDate has an unknown number of rows.

Can i get the output like below by using a query? I need the dates in one month to be columns and the value of the date columns will be values in the status column. The number of date records per studentID is the same its the number of dates in the attendanceDate filed that is unknown.

studentID   2010-03-17   2010-03-19   2010-03-20
------------------------------------------------    
1004            0            0            1

etc. This is for a creating a report so I need to do it in a query. Please help if you can.


You could use PIVOT. Take a look at this article.


Perhaps something using the SQL 2005 PIVOT clause? (see also: msdn)


Use a Matrix control in the report (or CrossTab in an Access report, or equivalent in your client tool)

SQL is a fixed column definition/contract language and you don't know how may columns you'll have. It's not really a SQL problem but a presentation problem.

Unless you use dynamic SQL PIVOT... not the SQL Server 2005+ PIVOT command which again is fixed, known columns

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜