使用 PIVOT 或 GROUP BY 技术将 MySQL 表中的行转换为列。
PIVOTING,一种数据转换技术,将行数据重新排列成列。在本例中,目标是按特定列(例如时间戳)对数据进行分组,并将每个数据值显示为单独的列。
而不是传统的 PIVOT 语法虽然在 MySQL 中并未得到广泛支持,但 SUM() 函数可以与 CASE 语句结合使用来达到所需的结果。
<code class="sql">SELECT d.data_timestamp , SUM(CASE WHEN data_id = 1 THEN data_value ELSE 0 END) AS 'input_1' , SUM(CASE WHEN data_id = 2 THEN data_value ELSE 0 END) AS 'input_2' ... , SUM(CASE WHEN data_id = 20 THEN data_value ELSE 0 END) AS 'input_20' FROM data GROUP BY data_timestamp ORDER BY data_timestamp ASC</code>
或者使用 IF 语句可以在 SUM() 函数中使用以获得相同的结果。
<code class="sql">SELECT d.data_timestamp , SUM(IF(data_id = 1, data_value, 0)) AS 'input_1' , SUM(IF(data_id = 2, data_value, 0)) AS 'input_2' ... , SUM(IF(data_id = 20, data_value, 0)) AS 'input_20' FROM data GROUP BY data_timestamp ORDER BY data_timestamp ASC</code>
另一种方法是使用多个 JOIN 语句来创建所需的输出。
<code class="sql">SELECT d.data_timestamp , d01.data_value AS 'input_1' , d02.data_value AS 'input_2' ... , d20.data_value AS 'input_20' FROM (SELECT DISTINCT d.data_timestamp FROM data ) AS d LEFT JOIN data AS d01 ON d01.data_timestamp = d.data_timestamp AND d01.data_id = 1 LEFT JOIN data AS d02 ON d02.data_timestamp = d.data_timestamp AND d02.data_id = 2 ... --- 20 JOINs LEFT JOIN data AS d20 ON d20.data_timestamp = d.data_timestamp AND d20.data_id = 20 ORDER BY d.data_timestamp ASC</code>
通过利用这些技术,您可以使用 GROUP BY 轻松地在 MySQL 中转置查询结果。
以上是如何使用 GROUP BY 在 MySQL 中透视查询结果?的详细内容。更多信息请关注PHP中文网其他相关文章!