我在表中有以下数据,并且需要获取数据透视表输出。我无法为自己的生命解决这个问题。预先感谢.....
mysql表中的行
id, timestamp, metric, value
1, 2020-10-31 02:52:02.144030, aaaa, 3
2, 2020-10-31 02:52:02.144030, tttt, 40
3, 2020-10-31 02:52:02.144030, vvvv, 6
4, 2020-10-31 02:53:01.656349, aaaa, 3
5, 2020-10-31 02:53:01.656349, tttt, 40
6, 2020-10-31 02:53:01.656349, vvvv, 6
7, 2020-10-31 02:54:02.053597, aaaa, 3
8, 2020-10-31 02:54:02.053597, tttt, 40
9, 2020-10-31 02:54:02.053597, vvvv, 6
10, 2020-10-31 02:55:01.490467, aaaa, 3
11, 2020-10-31 02:55:01.490467, tttt, 40
12, 2020-10-31 02:55:01.490467, vvvv, 6
我正在寻找的输出
timestamp, aaaa, tttt, vvvv
2020-10-31 02:52:02.144030, 3, 40, 6
2020-10-31 02:53:01.656349, 3, 40, 6
2020-10-31 02:54:02.053597, 3, 40, 6
2020-10-31 02:55:01.490467, 3, 40, 6
答案 0 :(得分:1)
您可以通过使用GROUP_CONCAT()
和CONCAT()
函数(例如
SET @sql = NULL;
SELECT GROUP_CONCAT(
CONCAT(
'MAX(CASE WHEN metric = "', metric,'" THEN value END ) AS ',metric
)
)
INTO @sql
FROM ( SELECT DISTINCT metric FROM tab) t;
SET @sql = CONCAT('SELECT timestamp,',@sql,' FROM tab GROUP BY timestamp');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;