-1

我有 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

我需要以下数据:

汽车品牌 | 零件数量 | DriversAmount

是否可以?完全加入后的计数在那里不起作用......

4

1 回答 1

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

你可以吗?

于 2012-11-16T09:42:53.353 回答