1

I want to transpose the resulting column to row without using ranking method in MYSQL.

select pid , phone  from mt where pid = 1 ; 

Result :

pid   phone
1     556
1     678

I want it in this format :

pid   phone1   phone2
1       556     678

Similarly if execute a query which has only 1 value like the one below

select pid , phone from mt where pid = 2 ;

it should result in both the columns phone1 and phone2 but phone2 column should be null like the following .

  pid   phone1     phone2
   2     123        NULL

How to proceed further ?

goonerboi
  • 309
  • 6
  • 18
  • Possible duplicate of [MySQL pivot row into dynamic number of columns](https://stackoverflow.com/questions/12004603/mysql-pivot-row-into-dynamic-number-of-columns) – cdaiga Nov 29 '17 at 03:04

1 Answers1

1

If there are only two values, you can use min() and max():

select pid, min(phone) as phone_1,
       (case when min(phone) <> max(phone) then max(phone) end) as phone_2
from t
group by pid;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786