2016-08-26 14 views
0

を示さない場合、私は名前、STUDENT_ID、date_of_exam、その結果、... 別resultテーブルを持っていstudentテーブルを持っているIDとDATEに基づいて一つのテーブルから1行を取り、別のテーブルに複数の行を取得しますstudent_id、test_name、マーク test_nameとマークは複数の行になります。 テスト数は動的です。静的ではありません。のmysql - NULL値に

私は私のレポートのヘッダーやショーマークなど 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

使用PIVOT表 –

+0

号は、ピボットを気にしないでください。アプリケーションのコードで表示の問題を処理するだけです。 – Strawberry

+0

問題は私はすべての学生IDを取る必要がありますし、列としてヘッダー内のすべてのテスト名を持つ必要があります..これらの値をExcelで押しています。 –

答えて

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 

SQLfiddle demo

+0

これはtest3に限定されない複数のテストになります –