【发布时间】:2022-01-22 23:16:23
【问题描述】:
我的 MariaDB 表如下所示:
| Component | Timestamp | Duration |
|---|---|---|
| Component one | 2021-10-01 14:04:54 | 40 |
| Component one | 2021-11-01 14:04:45 | 10 |
| Component one | 2021-11-11 11:05:23 | 20 |
| Component one | 2021-12-01 13:04:43 | 20 |
| Component one | 2021-12-12 12:14:11 | 30 |
| Component two | 2021-11-01 14:04:27 | 45 |
| Component two | 2021-12-01 13:04:08 | 23 |
我想做的是显示过去三个月中每个组件的平均持续时间。它应该看起来像这样:
| Component | AVG Duration (October) | AVG Duration (November) | AVG Duration (December) |
|---|---|---|---|
| Component one | 40 | 15 | 25 |
| Component two | 45 | 23 |
我尝试弄乱我在网上找到的数据透视表,但下面的查询仍然导致多行(每个月 1 行,该行其他月份为空)
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT('(IF(MONTHNAME(s.LOG_TIMESTAMP) = "', MONTHNAME(`LOG_TIMESTAMP`),'", AVG(`DURATION`),"")) AS ',MONTHNAME(LOG_TIMESTAMP) )
) INTO @sql
FROM table1;
SET @sql = CONCAT('SELECT s.COMPONENT, ', @sql, '
FROM table1 s
GROUP BY s.COMPONENT, MONTHNAME(s.LOG_TIMESTAMP)
ORDER BY s.COMPONENT');
SELECT @sql;
PREPARE stmt FROM @sql;
EXECUTE stmt;
因此,如果我运行该查询,组件 1 的输出(例如)如下所示:
| Component | AVG Duration (October) | AVG Duration (November) | AVG Duration (December) |
|---|---|---|---|
| Component one | 40 | ||
| Component one | 15 | ||
| Component one | 25 |
这可能是具有 log_timestamp 的 group-by 表达式,但如果我删除它,concat 函数只会写入第一个可用月份的平均持续时间(所有月份)。我对数据透视表没有任何经验,所以我在这里有点超出我的深度。任何帮助将不胜感激。
【问题讨论】:
标签: mysql mariadb pivot-table