将MYSQL行值转换为列名

时间:2019-04-09 08:42:23

标签: mysql

我有这样的表:

job_status_air

status_id  | status
-----------+------------
1          | AIRPORT IN
2          | AIRPORT OUT

job_status_air_pkg

id  | status_id  | package_no
----+------------+------------
1   | 1          | pkg1
2   | 1          | pkg2
3   | 1          | pkg3
4   | 2          | pkg1

我正在使用以下查询:

select package_no , 
       (case when job_status_air.status = "AIRPORT IN" then job_status_air_pkg.id end) AIRPORTIN, 
       (case when job_status_air.status = "AIRPORT OUT" then job_status_air_pkg.id else 0 end) AIRPORTOUT 
FROM job_status_air_pkg 
LEFT JOIN job_status_air ON (job_status_air.status_id = job_status_air_pkg.status_id) 
WHERE job_status_air.mawb = 'awb1' or hawb = 'awb1' 

我无法达到以下结果:

package_no | AIRPORT IN | AIRPORT OUT
-----------+------------+-------------
 pkg1      |    1       |  4
 pkg2      |    2       |
 pkg3      |    3       |

有人可以帮我吗?

1 个答案:

答案 0 :(得分:2)

您需要应用聚合和分组依据

select package_no , 
       max(case when job_status_air.status = "AIRPORT IN" then job_status_air_pkg.id end) AIRPORTIN, 
       max(case when job_status_air.status = "AIRPORT OUT" then job_status_air_pkg.id else 0 end) AIRPORTOUT 
FROM job_status_air_pkg 
LEFT JOIN job_status_air ON (job_status_air.status_id = job_status_air_pkg.status_id) 
WHERE job_status_air.mawb = 'awb1' or hawb = 'awb1' 
group by package_no