简体   繁体   中英

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  |
+---------+------+--------+------+

I want output like below

+-------+-------+-------+-------+------+-----
| id    | 1990  | 1991  | 1992  |1993  | 1994 |
+-------+-------+-------+-------+------+------
|  1    |  10(a) | 20(b) | 30(c)| 40(d)| 50(e)|
-----------------------------------------------

You can make the statement as follows:

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;

Here is the working fiddle

Use conditional aggregation. I think that it makes more sense to put the bands and scores in separate columns, so:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM