我在mysql中有这个表,但不知道如何以我所需的格式显示结果。
标记(表)
ID student_id class_id subject_id obtained_marks total_marks 1 1 1 11 68 100 2 2 1 11 63 100 3 3 1 11 61 100 4 1 1 12 45 100 5 2 1 12 75 100 6 3 1 12 61 100 7 1 1 13 42 100 8 2 1 13 84 100 9 3 1 13 78 100
其中subject_id 11 =英语,12 =数学,13 =科学。现在我想显示那样的结果表
Student_id English Math Science 1 68 63 61 2 45 75 84 3 61 61 78
有谁能告诉我如何形成这种查询?
答案 0 :(得分:0)
尝试pivoting data like this
Select * from table
Pivot
(
Max (obtainedmarks)
For studentid in ([english],[math],[science])
)
Group by studentid
答案 1 :(得分:0)
在mysql中进行数据透视的最好方法,虽然我没有尝试过你的情况,但下面的sql应该可以正常工作
select
student_id,
SUM(english) as english,
SUM(math) as math,
SUM(science) as science
FROM (
SELECT
student_id,
CASE WHEN subject_id = 11 THEN obtained_marks else 0 end as English ,
CASE WHEN subject_id = 12 THEN obtained_marks else 0 end as Math ,
CASE WHEN subject_id = 13 THEN obtained_marks else 0 end as science
from marks
)tmp
group by student_id
你可以运行像
这样的查询select * from subjects
动态创建下面的SQL
CASE WHEN subject_id = 11 THEN obtained_marks else 0 end as English ,
CASE WHEN subject_id = 12 THEN obtained_marks else 0 end as Math ,
CASE WHEN subject_id = 13 THEN obtained_marks else 0 end as science
即
foreach($subject as $id=>$name){
$sql.=CASE WHEN subject_id = $id THEN obtained_marks else 0 end as $name,
}
答案 2 :(得分:0)
select t.student_id,sum(t.english) as English,sum(t.maths) as Maths,
sum(t.science) as Science from
(select student_id,case when subject_id=11 then obtained_marks else 0 end as english,
case when subject_id =12 then obtained_marks else 0 end as maths,
case when subject_id =13 then obtained_marks else 0 end as science from Marks) as
t group by t.student_id
答案 3 :(得分:-1)
您应该像这样更改表格结构
ID student_id class_id english_marks Maths_marks science_marks
1 1 1 11 68 55
然后你可以在它的方面获取每一行TABLE HEAD
<table>
<th>Student_id</th>
<th>English</th>
<th>Math</th>
<th>Science<th>
while($fetch = mysql_fetch_array($sql))
{
echo '<td>'.$fetch[student_id].'</td>';
echo '<td>'.$fetch[english_marks].'</td>';
echo '<td>'.$fetch[Maths_marks].'</td>';
echo '<td>'.$fetch[science_marks].'</td>';
}
</table>
这是一种很好的方法:)