我有一个student
表,其中包含name,student_id,date_of_exam,result,..
另一个result
表,其中包含student_id,test_name,mark
test_name和标记将是多行。
测试次数是动态的..它不是静态的。
我需要table2.test_name
作为标题并在报告中显示标记
表1
| id | name | date_of_exam|result|
------------------------------------------------
| 1 | gg | 24-08-2016 | pass |
| 2 | hh | 24-08-2016 | pass |
| 3 | ee | 25-08-2016 | abse |
表2
| student_id | test_name |mark |
-------------------------------------------------
| 1 | test1 | 20 |
| 1 | test2 | 40 |
| 1 | test3 | 50 |
| 2 | test1 | 30 |
| 2 | test2 | 50 |
输出应为
| id | name | date_of_exam|result| test1 | test2 |test3 |
---------------------------------------------------------
| 1 | gg | 24-08-2016 | pass | 20 | 40 | 50 |
| 2 | hh | 24-08-2016 | pass | 30 | 50 | NULL |
| 3 | ee | 25-08-2016 | abse | NULL | NULL | NULL |
答案 0 :(得分:0)
尝试使用CASE和分组:
SELECT table1.id,MAX(table1.name),MAX(table1.date_of_exam),MAX(table1.result),
MAX(CASE WHEN table2.test_name = 'test1' THEN table2.mark END) as test1,
MAX(CASE WHEN table2.test_name = 'test2' THEN table2.mark END) as test2,
MAX(CASE WHEN table2.test_name = 'test3' THEN table2.mark END) as test3
FROM table1
LEFT JOIN table2 ON (table1.id=table2.student_id)
GROUP BY table1.Id