如何在html和php中制作PIVOT(交叉表)

如何在html和php中制作PIVOT(交叉表),php,html,mysql,Php,Html,Mysql,如果有人能解决这个问题,对我将是一个很大的帮助。 我有一个MySql数据库表,其中包含以下记录: student_id subject_id scores s01 eng01 10.00 s01 math01 10.00 s01 science01 10.00 s01 physic01 10.00 s02 eng01 20

如果有人能解决这个问题,对我将是一个很大的帮助。 我有一个MySql数据库表,其中包含以下记录:

student_id    subject_id    scores
s01           eng01         10.00
s01           math01        10.00
s01           science01     10.00
s01           physic01      10.00
s02           eng01         20.00
s02           math01        20.00
s02           science01     20.00
s02           physic01      20.00
我想用html和php这样的方式显示

student    eng01    math01    science01    physic01
s01        10       10        10           10
s02        20       20        20           20

我已经完成了不同的sql查询集和php代码,但仍然无法完成。非常感谢您的帮助

如果您事先知道所有主题名称,您可以使用
CASE
表达式创建透视表:

SELECT student_id,
    MAX(CASE WHEN subject_id = 'eng01' THEN scores ELSE 0 END) AS eng01,
    MAX(CASE WHEN subject_id = 'math01' THEN scores ELSE 0 END) AS math01,
    MAX(CASE WHEN subject_id = 'science01' THEN scores ELSE 0 END) AS science01,
    MAX(CASE WHEN subject_id = 'physic01' THEN scores ELSE 0 END) AS physic01
FROM students
GROUP BY student_id
输出(用于示例数据)

如果您不知道所有主题名称,可以使用此查询获取列表:

SELECT DISTINCT subject_id FROM students
然后,在PHP中,您可以创建一个循环,根据这个循环的结果构建查询,类似于(假设您在一个名为
$result
的变量中有该查询的结果)这个循环。请注意,此代码还保存了主题名称,以便以后用于输出表的标题行

$sql = 'SELECT student_id';
$headings = array();
while ($row = $result->fetch_array()) {
   $sql .= ", MAX(CASE WHEN subject_id = '{$row['subject_id']}' THEN scores ELSE 0 END) AS {$row['subject_id']}";
   $headings[] = $row['subject_id'];
}
$sql .= ' FROM students GROUP BY student_id';
// run query
要将这些数据输出到HTML表中,可以使用类似这样的代码。我再次假设查询的输出在
$result
中:

echo "<table>\n<thead><tr><th>Student ID</th><th>" . implode('</th><th>', $headings) . "</th></tr></thead>\n<tbody>";
while ($row = $result->fetch_array()) {
    echo "<tr><td>{$row['student_id']}</td>";
    foreach ($headings as $h) {
        echo "<td>{$row[$h]}</td>";
    }
    echo "</tr>\n";
}
echo "</tbody></table>\n";
echo“\n学生ID”。内爆(“”,$headers)。“\n”;
而($row=$result->fetch_array()){
回显“{$row['student_id']}”;
foreach(标题为$h){
回显“{$row[$h]}”;
}
回音“\n”;
}
回音“\n”;

谢谢您的评论。我在查询中已经这样做了,但我更可能通过web显示输出:(顺便说一句,html)。@MarkC你需要在你的问题中更加清楚你到底在问什么。我明白了:)这对我帮助很大。非常感谢。你能告诉他如何在HTML表格中显示记录吗?
echo "<table>\n<thead><tr><th>Student ID</th><th>" . implode('</th><th>', $headings) . "</th></tr></thead>\n<tbody>";
while ($row = $result->fetch_array()) {
    echo "<tr><td>{$row['student_id']}</td>";
    foreach ($headings as $h) {
        echo "<td>{$row[$h]}</td>";
    }
    echo "</tr>\n";
}
echo "</tbody></table>\n";