如何在php mysql中将行值动态转换为列名

时间:2018-08-30 08:40:01

标签: php mysql dynamic pivot crosstab

我有一个名为“ pivo”的表,其中带有列(ID,名称,课程,标记)。我想将“名称”列数据转换为行标题,将“课程”列数据转换为列标题,并将“标记”列数据转换为行数据,以用于从“课程”列数据转换而来的那些列。请记住忽略“ ID”列及其选择查询中的数据。

我尝试过:

// Select Students with their Marks Dynamically

$SelectQuery3 = mysqli_query($connection, "SELECT distinct Course FROM pivo");
$numrows3     = mysqli_num_rows($SelectQuery3);
if ( ! $SelectQuery3)
{
    die ("Sorry, database selection failed1. " . mysqli_connect_error());
}
else if ($numrows3 != 0)
{
    echo "  
        <caption><h3>Students with their Marks Dynamically Head</h3></caption>
        <table border = '1' style = 'border-collapse: collapse;'>
            <thead>
                <tr>
                    <th>Name</th>
        ";
    $Crs = "";
    while ($display3 = mysqli_fetch_array($SelectQuery3))
    {
        $Crs = $display3 [0];
        echo "<th>{$display3 ['0']}</th>";
    }
    echo "
                    <th>Total</th>
                    <th>Average</th>
                </tr>
            </thead>
            <tbody>";

    $SelectQuery4 = mysqli_query($connection, "select `Name`,
                sum(case when `Course` = '$Crs' then `Marks` else 0 end) '$Crs'
                from pivo group by `Name`");
    $numrows4     = mysqli_num_rows($SelectQuery4);
    if ( ! $SelectQuery4)
    {
        die ("Sorry, database selection failed2. " . mysqli_connect_error());
    }
    else if ($numrows4 != 0)
    {
        while ($display4 = mysqli_fetch_array($SelectQuery4))
        {
            echo "
                            <tr>
                                <td>{$display4 ['0']}</td>
                                <td>{$display4 ['1']}</td>
                            </tr>";
        }
    }
    else
    {
        echo "<div class='alert alert-info'> Sorry, no student found yet. </div>";
    }

    echo "          
            </tbody>
        </table>";
}
else
{
    echo "<div class='alert alert-info'> Sorry, no course found yet. </div>";
}

并得到错误的结果。

有人可以帮忙。

谢谢。

0 个答案:

没有答案