snippetsqlMinor
How to get multiple row data into a row with multiple columns
Viewed 0 times
columnswithintogetmultiplehowrowdata
Problem
I have a MySQL table like this:
How can I get data a result like this:
User_Id course_name course_location course_id
1 course name 1 location 1 1
1 course name 2 location 2 2
1 course name 3 location 1 3
2 course name 2 location 1 2
2 course name 4 location 4 4How can I get data a result like this:
User_id course 1 course2 course3 course4
1 yes-location1 yes-location2 yes-location1 NULL
2 NULL yes-location1 NULL yes-location4Solution
You must Pivot data using
Query:
Sample query in SQL Fiddle.
You can replace
Output:
GROUP BY with MAX aggregate and use CASE to filter by User_id.Query:
SELECT User_id
, MAX(
CASE WHEN course_id = 1 THEN course_location END
) as Course_1
, MAX(CASE WHEN course_id = 2 THEN course_location END) as Course_2
, MAX(CASE WHEN course_id = 3 THEN course_location END) as Course_3
, MAX(CASE WHEN course_id = 4 THEN course_location END) as Course_4
FROM data
GROUP BY User_id;Sample query in SQL Fiddle.
You can replace
course_location by CONCAT('YES-', course_location) is the leading YES is indeed needed.Output:
User_Id | Course_1 | Course_2 | Course_3 | Course_4
1 | location 1 | location 2 | location 1 | (null)
2 | (null) | location 1 | (null) | location 4Code Snippets
SELECT User_id
, MAX(
CASE WHEN course_id = 1 THEN course_location END
) as Course_1
, MAX(CASE WHEN course_id = 2 THEN course_location END) as Course_2
, MAX(CASE WHEN course_id = 3 THEN course_location END) as Course_3
, MAX(CASE WHEN course_id = 4 THEN course_location END) as Course_4
FROM data
GROUP BY User_id;User_Id | Course_1 | Course_2 | Course_3 | Course_4
1 | location 1 | location 2 | location 1 | (null)
2 | (null) | location 1 | (null) | location 4Context
StackExchange Database Administrators Q#129611, answer score: 9
Revisions (0)
No revisions yet.