我有两张表如下
车辆表
Vehicle_id | Location | Status
------------------------------
1000 | FLT1 | OPERATING
1001 | FLT1 | OPERATING
. | . | .
. | . | .
Run Code Online (Sandbox Code Playgroud)
和Vehicle_Specs表
Vehicle_id | AttribID | AttribValue
------------------------------
1000 | Model | F150
1000 | Driver | John Smith
1000 | Odometer | 80000
1001 | Model | F350
1001 | Driver | Joe Douglas
1001 | Odometer | 50000
Run Code Online (Sandbox Code Playgroud)
我很难使用SQL实现以下目标.
返回车辆状态为"正在运行"的所有vehicle_ids及其驱动程序,其型号为F150.我的问题是如何创建一个子查询来在我的select语句和where子句的第二个表中获取两个AtrribValues.
使用a PIVOT然后您只需要对Vehicle_specs表进行单个表扫描:
SELECT v.vehicle_id,
s.Driver
FROM ( SELECT *
FROM Vehicle_specs
PIVOT ( MAX( attribvalue )
FOR AttribID IN ( 'Model' AS model, 'Driver' AS Driver ) )
) s
INNER JOIN
vehicle v
ON ( v.vehicle_id = s.vehicle_id )
WHERE s.model = 'F150'
AND v.status = 'OPERATING'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
59 次 |
| 最近记录: |