[英]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.