超过2个表的多个JOIN

时间:2012-11-16 09:24:54

标签: sql-server sql-server-2008-r2

我有3张桌子:

Cars
-----------------
CarBrand | Amount
 Honda   |  0
 Mitsu   |  5
 Ford    |  7

CarParts
--------------------
CarPartID | CarBrand
 001      |  Honda
 002      |  Mitsu
 003      |  Ford
 004      |  Ford
 005      |  Ford

Drivers
-----------------------
DriverName  |  CarBrand
 Tom        |  Ford
 John       |  Mitsu
 Mark       |  Mitsu

我需要在结果中跟踪数据:

CarBrand | PartsAmount | DriversAmount

有可能吗?完全加入后计数在那里不起作用......

1 个答案:

答案 0 :(得分:1)

这里有几种方法可以做你想做的事:SQLFiddle

select c.CarBrand, j.parts, k.drivers
from
   Cars c
cross apply
(
    select count(*)
    from CarParts cp
    where cp.CarBrand = c.CarBrand
) j (parts)
cross apply
(
    select count(*)
    from Drivers d
    where d.CarBrand = c.CarBrand
) k (drivers);

select
  c.CarBrand,
  (select count(*) from CarParts cp where cp.CarBrand = c.CarBrand) as Parts,
  (select count(*) from Drivers d where d.CarBrand = c.CarBrand) as Drivers
from
  Cars C

这对你好吗?