问题
I have three MySql tables:
Students - StudentId, StudentName
Assessments - AssessmentId, AssessmentName
Results - StudentId, AssessmentId, Grade
I can't predetermine the number of students or assessments, as these are created by users.
How can I select a two-way table, showing the results of all students' assessments (which will have an unpredetermined number of rows and columns):
|--------|---------|---------|---------|---------|---------|
|User |Test A |Test B |Test C |Test D |Test E |
|--------|---------|---------|---------|---------|---------|
|Alex |A |A |C |Null |F |
|Ben |Null |D |A |Null |Null |
|--------|---------|---------|---------|---------|---------|
I am looking to do this either in a SQL select, or using LINQ to Entities in ASP.NET, if that has an efficient method for achieving the same.
Thank you.
回答1:
You cannot achieve this in a single SQL query. You will need a function that will generate a result-set with variable columns and then make a select from it.
回答2:
I don't think you can create a pivot or crosstab directly in MySQL. You could select the results ordered by user, test then rearrange them into a cross tab. See e.g.
Is it possible to Pivot data using LINQ?
Linq: How to transform rows to columns with a count (Crosstab data)?
来源:https://stackoverflow.com/questions/6040991/select-a-two-way-table-in-mysql