我想在MYSQL中不使用ranking方法将结果列转换成行。

select pid , phone  from mt where pid = 1 ;

Result :

pid   phone
1     556
1     678

我想要这种格式:
pid   phone1   phone2
1       556     678

类似地,如果执行一个只有1个值的查询,如下面所示
从mt中选择pid,phone,其中pid=2;
它应该导致phone1和phone2列,但是phone2列应该为空,如下所示。
  pid   phone1     phone2
   2     123        NULL

如何进一步?

最佳答案

如果只有两个值,则可以使用min()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;

07-25 21:51
查看更多