问题
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.
回答1:
You could use PIVOT. Take a look at this article.
回答2:
Perhaps something using the SQL 2005 PIVOT clause? (see also: msdn)
回答3:
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
来源:https://stackoverflow.com/questions/2482398/sql-rows-to-columns-conversion