-1

我是 SQL 新手。我有两张桌子,CarDescCarCost。CarDesc驱动查询人口。我正在尝试选择CAR_DESCwhere ID In List(1,2,3),然后将ID加入CarCost表以返回2D cost列和4D cost列。

汽车描述

ID   CAR_DESC  COUNTRY
1    Toyota    Japan
2    Honda     Japan
3    Kia       Korea
4    Jeep      USA
5    Ford      USA

汽车成本

ID   TYPE   COST
1    2D     3000
1    4D     2700
2    2D     4000
2    4D     5500
3    2D     3200
3    4D     5000

这是我试图收到的预期结果:每个汽车描述都有一个不同的记录,然后是2D 成本的列,然后是4D 成本的列

CAR_DESC 2D_COST  4D_COST
Toyota   3000     2700
Honda    4000     5500
Kia      3200     5000

我认为我对 SQL 很熟悉,但在调整代码时,我不断收到不同的错误消息。你们能帮我解决我的SQL吗?这是我目前所拥有的......

SELECT DESC 
FROM CarDesc
WHERE ID IN LIST (1,2,3)
LEFT JOIN (SELECT COST AS 2D_COST
           WHERE TYPE = 2D)
     ON CarDesc.ID = CarCost.ID
LEFT JOIN (SELECT COST AS 4D_COST
           WHERE TYPE = 4D)
     ON CarDesc.ID = CarCost.ID
4

2 回答 2

1

查询将如下所示:

SELECT cd.*, cc2.cost as cost_2d, cc4.cost as cost_4d
FROM CarDesc cd LEFT JOIN
     CarCost cc2
     ON cd.Id = cc2.id AND cc2.TYPE = '2D' LEFT JOIN
     CarCost cc4
     ON cd.Id = cc4.id AND cc4.TYPE = '4D'
WHERE cd.ID IN (1, 2, 3);

您的查询中有许多错误。不值得试图解释它们。检查此查询以了解它应该如何工作。

于 2016-11-05T13:18:37.523 回答
0
 SELECT cd.ID ,
 sum(case when cc.type='2D' then cc.cost else 0 end) 2D_COST,  
 sum(case when cc.type='4D' then cc.cost else 0 end) 4D_COST
 FROM CarDesc cd LEFT JOIN CarCost cc ON cd.Id = cc.id 
 WHERE cd.ID IN (1, 2, 3)
 group by cd.ID 
于 2016-11-05T14:14:44.460 回答