0

I am wodering is it possible to use a pivot table to make the col as rows without using any mysql functions and GROUP AS.

Here's the table

+----+------+------+------+
| id | col1 | col2 | col3 |
+----+------+------+------+
|  1 |    1 |    2 |    6 |
|  2 |    7 |    4 |    8 |
|  3 |    4 |    1 |    5 |
+----+------+------+------+

Here's the desired output iam looking for. The header is the id

+---+---+---+
| 1 | 2 | 3 |
+---+---+---+
| 1 | 7 | 4 |
| 2 | 4 | 1 |
| 6 | 8 | 2 |
+---+---+---+  
2
  • Are there only 3 rows in the table? Commented Dec 24, 2019 at 12:42
  • @Dexter . . . What could you possibly mean by "without using any mysql functions"? Commented Dec 24, 2019 at 13:51

1 Answer 1

4

This is painful, but you can do:

select max(case when id = 1 then col end) as id_1,
       max(case when id = 2 then col end) as id_2,
       max(case when id = 3 then col end) as id_3       
from ((select id, col1 as col, 1 as which from t) union all
      (select id, col2 as col, 2 as which from t) union all
      (select id, col3 as col, 3 as which from t)
     ) ic
group by which;

Note that this only works for the data that you have provided. If you have additional columns or rows, you would need to modify the query.

Here is a db<>fiddle.

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

8 Comments

Are those not functions?
@gordon Linoff this is great. will try it. Thanks
@Strawberry . . . I actually interpreted that as "user-defined functions". But I totally get how that is interpreting something in the question that might not be there.
@GordonLinoff I have 100 id's in the table and is it advisable to do the case for each individual id's? I can see why you said it is painful.
@Dexter . . . You can generate the code using a spreadsheet or SQL query.
|

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.