0
+---------+------+--------+------+
|   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)|
-----------------------------------------------
1
  • 3
    MySQL <> SQL Server <> Postgres <> SQLite! Pleas tag only the one database you are running. Commented Oct 9, 2020 at 18:01

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

Hey , thanks for your reply .What if we have 50k ids having band and score values for the last 50 years.
@sakthi.nagulsamy: you need one (actually, two) expressions per year, that's how conditional aggregation works. Otherwise, you need dynamic SQL, which is much more complicated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.