转换 SQL 查询结果的 table 结构(透视)
Transform table structure of SQL query result (pivot)
我有一个 table 来自具有以下内容结构的查询:
+-----+-----------+-------+
|date | sensor_id | power |
+-----+-----------+-------+
|date1| 1 | 0.51 |
|date1| 2 | 0.52 |
|date1| 3 | 0.53 |
|date2| 1 | 0.61 |
|date2| 2 | 0.61 |
|date2| 3 | 0.63 |
|date3| 1 | 0.71 |
|date3| 2 | 0.72 |
|date3| 3 | 0.73 |
+-----+-----------+-------+
有没有办法使用 SQL 将此 table 转换为以下内容?
+-----+-----------+------------+-----------+
|date | 1 | 2 | 3 |
+-----+-----------+------------+-----------+
|date1| 0.51 | 0.52 | 0.53 |
|date1| 0.61 | 0.62 | 0.63 |
|date1| 0.71 | 0.72 | 0.73 |
+-----+-----------+------------+-----------+
是的,这是可能的,并且是调用 "Pivot"
检查这个.. Pivot in Mysql
select *
from table
group by sensor_id
如果您事先知道 sensor_id
的可能值集是什么,您可以使用条件聚合来进行数据透视:
select
date,
max(case when sensor_id = 1 then power else 0 end) as "1",
max(case when sensor_id = 2 then power else 0 end) as "2",
max(case when sensor_id = 3 then power else 0 end) as "3"
from Table1
group by date;
如果您不知道所有可能的值,您可以使用动态 sql 来构建适当的语句;该查询特定于 MySQL:
SET @sql = NULL;
SELECT
GROUP_CONCAT(
DISTINCT CONCAT(
'MAX(CASE WHEN sensor_id = ',
sensor_id,'
THEN power ELSE 0 END) AS "',
sensor_id,'"'
)
) INTO @sql FROM Table1;
SET @sql = CONCAT(
'SELECT date, ',
@sql,
' FROM Table1 GROUP BY date'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
查看此 SQL Fiddle 示例。
我有一个 table 来自具有以下内容结构的查询:
+-----+-----------+-------+
|date | sensor_id | power |
+-----+-----------+-------+
|date1| 1 | 0.51 |
|date1| 2 | 0.52 |
|date1| 3 | 0.53 |
|date2| 1 | 0.61 |
|date2| 2 | 0.61 |
|date2| 3 | 0.63 |
|date3| 1 | 0.71 |
|date3| 2 | 0.72 |
|date3| 3 | 0.73 |
+-----+-----------+-------+
有没有办法使用 SQL 将此 table 转换为以下内容?
+-----+-----------+------------+-----------+
|date | 1 | 2 | 3 |
+-----+-----------+------------+-----------+
|date1| 0.51 | 0.52 | 0.53 |
|date1| 0.61 | 0.62 | 0.63 |
|date1| 0.71 | 0.72 | 0.73 |
+-----+-----------+------------+-----------+
是的,这是可能的,并且是调用 "Pivot" 检查这个.. Pivot in Mysql
select *
from table
group by sensor_id
如果您事先知道 sensor_id
的可能值集是什么,您可以使用条件聚合来进行数据透视:
select
date,
max(case when sensor_id = 1 then power else 0 end) as "1",
max(case when sensor_id = 2 then power else 0 end) as "2",
max(case when sensor_id = 3 then power else 0 end) as "3"
from Table1
group by date;
如果您不知道所有可能的值,您可以使用动态 sql 来构建适当的语句;该查询特定于 MySQL:
SET @sql = NULL;
SELECT
GROUP_CONCAT(
DISTINCT CONCAT(
'MAX(CASE WHEN sensor_id = ',
sensor_id,'
THEN power ELSE 0 END) AS "',
sensor_id,'"'
)
) INTO @sql FROM Table1;
SET @sql = CONCAT(
'SELECT date, ',
@sql,
' FROM Table1 GROUP BY date'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
查看此 SQL Fiddle 示例。