Select a two-way table in MySql

安稳与你 提交于 2020-03-05 07:35:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!