使用PHP格式化SQL查询结果以使其水平显示

时间:2019-04-13 02:53:10

标签: php sql

我正在尝试以所示格式显示查询

    Size Group  Year1   Year2  Year 3   Year 4
    Small       data     data   data     data (this row data are related to small associated with each year)
    Med         data     data   data     data (this row data are related to Med associated with each year)
    Large       data     data   data     data (this row data are related to Large associated with each year)

我能够垂直显示数据,但是我不知道如何水平显示数据,第1、2、3、4年继续进行

我有以下代码可垂直显示数据
HTML:

<table>
    <thead>
    <tr>
        <th scope="col">year</th>
        <th scope="col">small</th>
        <th scope="col">medium</th>
        <th scope="col">large</th>
        <th scope="col">extra large</th>

    </tr>
    </thead>
    <tbody>
     <?php table($conn) ?>
    </tbody>
</table>

PHP

$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        echo "<tr>" . "<td>$row[yr]</td>" . "<td>$row[small]</td>" . "<td>$row[medium]</td>" . "<td>$row[large]</td>". "<td>$row[extralarge]</td>";
    }
} else {
    echo "Fail to query ";
}

此代码的输出:

Year Small Medium Large ExtraLarge
2001  12    13     14    15    
2002  12    13     14    15    
2003  12    13     14    15    

需求显示,年份动态显示水平

Size Group    2001 2002 2003
Small          12   12  12
Medium         13   13  13
Large          14   14  14
Extralarge     15   15  15

1 个答案:

答案 0 :(得分:0)

在这里,我试图模拟我对您问题的理解。你可以试试看希望对您有帮助:)

 CREATE TABLE size_group_data_by_year( year int, small int, medium int, large int, extralarge int);

INSERT INTO size_group_data_by_year VALUES 
(2001,  12,    13,     14,    15),   
(2002,  12,    13,     14,    15),  
(2003,  12,    13,     14,    15);

DECLARE @columns NVARCHAR(MAX), @columns1 NVARCHAR(MAX), @sql NVARCHAR(MAX);

SELECT @columns = STUFF((
            SELECT DISTINCT ',' + '[' + CAST(year AS VARCHAR) +']'  FROM size_group_data_by_year
            FOR XML PATH('')
            ), 1, 1, '')
FROM size_group_data_by_year;

SET @sql = 'SELECT size_group,'+ @columns + 'FROM
(
SELECT year, size_group, data
FROM size_group_data_by_year
UNPIVOT (
     data FOR size_group IN (
        [small],[medium],[large],[extralarge]
    )
) unpvt
) AS src
PIVOT
(
  MAX(data) FOR year IN ('+@columns+')
) AS p;';

EXEC sp_executesql @sql;

您可以在这里找到此模拟:https://rextester.com/ZALB59809