[英]mysql Select values from multiple different columns values into single column(PIVOT)
+---------+------+--------+------+
| year | id | band | score |
+---------+------+--------+------+
| 1990 | 1 | a | 10 |
| 1991 | 1 | b | 20 |
| 1992 | 1 | c | 30 |
| 1993 | 1 | d | 40 |
| 1994 | 1 | e | 40 |
+---------+------+--------+------+
我想要如下所示的 output
+-------+-------+-------+-------+------+-----
| id | 1990 | 1991 | 1992 |1993 | 1994 |
+-------+-------+-------+-------+------+------
| 1 | 10(a) | 20(b) | 30(c)| 40(d)| 50(e)|
-----------------------------------------------
您可以按如下方式进行声明:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'max(case when year = ''',
year,
''' then concat(score,''','(''',',band,',''')',''') end) year_',
year
)
) INTO @sql
FROM
mytable;
SET @sql = CONCAT('SELECT id, ', @sql, '
FROM mytable
GROUP BY id');
select @sql;
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
这是工作小提琴
使用条件聚合。 我认为将乐队和分数放在单独的列中更有意义,因此:
select id,
max(case when year = 1990 then score end) score_1990,
max(case when year = 1990 then band end) band_1990,
max(case when year = 1991 then score end) score_1991,
max(case when year = 1991 then band end) band_1991,
...
from mytable
group by id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.