拆分1列到2 mysql

ve7v8dk2  于 2022-12-26  发布在  Mysql
关注(0)|答案(1)|浏览(140)

我有这个表数据
| 汽车|类型|
| - ------|- ------|
| 充电器|男|
| 挑战者|男|
| 野马|男|
| 法拉利|S型|
| 兰博|S型|
| 布加蒂|S型|

预期产出:

| 肌肉卡|超级跑车|
| - ------|- ------|
| 充电器|法拉利|
| 挑战者|兰博|
| 野马|布加蒂|
我尝试使用select case,但得到的是null

select  
   case when type = 'M' then cars end Musclecar ,
   case when type = 'P' then cars end Supercar 
from carlist

当前输出

| Musclecar | Supercar |
| --------  | -------- |
| charger   | null     |
| challenger| null     |
| mustang   | null     |
| null      | ferrari  |
| null      | lambo    |
| null      | buggati  |
wgx48brx

wgx48brx1#

一种方法是将CASE语句和ROW_NUMBER函数组合使用,如下所示:

SELECT
    MAX(CASE WHEN type = 'M' THEN cars END) AS Musclecar,
    MAX(CASE WHEN type = 'S' THEN cars END) AS Supercar
FROM (
    SELECT
        cars,
        type,
        ROW_NUMBER() OVER (PARTITION BY type ORDER BY cars) AS row_num
    FROM carlist
) t
GROUP BY row_num;
这将产生以下输出:
| Musclecar | Supercar |
| --------  | -------- |
| charger   | ferrari  |
| challenger| lambo    |
| mustang   | buggati  |

相关问题