0

我在我的项目中使用了四个表,分别是 VehicleMaster、OwnerMaster、CustomerMaster 和 CustomerVehicle

顾名思义,前三个是主表,最后一个表 (CustomerVehicle) 包含 CustomerID 和 VehicleID。表层次结构如下

 OwnerMaster (OwnerID, OwnerName) 
 VehicleMaster (VehicleID, OwnerID, VehicleDetails blah blah...) 
 CustomerMaster (CustomerID, CustomerName..) 
 CustomerVehicle     (CustomerID, VehicleID)

现在我想知道每个车主有多少辆车在运行。输出应该是这样的。

OwnerName, TotalVehicles, No of Running Vehicles, NonRunning Vehicles.
xxxx, 40, 34, 6

任何帮助都感激不尽。谢谢,

4

3 回答 3

1

像这样的东西应该有效;左加入表格并(不同)计算各个字段;

SELECT om.OwnerName, 
       COUNT(DISTINCT vm.VehicleID) TotalVehicles, 
       COUNT(DISTINCT cv.VehicleID) Running, 
       COUNT(DISTINCT vm.VehicleID)-COUNT(DISTINCT cv.VehicleID) NotRunning
FROM OwnerMaster om
LEFT JOIN VehicleMaster vm ON om.OwnerID = vm.OwnerID
LEFT JOIN CustomerVehicle cv ON vm.VehicleID = cv.VehicleID
GROUP BY om.OwnerID, om.OwnerName

一个用于测试的 SQLfiddle

于 2013-10-07T19:35:36.427 回答
0

可能有没有车辆的车主,我们不知道......这样的事情也应该起作用:

SELECT 
  om.OwnerName,
  count(vm.VehicleID) Total,
  sum(case when vm.VehicleID is not null 
            and cv.VehicleID is not null then 1 else 0 end) Runnng,
  sum(case when vm.VehicleID is not null 
            and cv.VehicleID is null then 1 else 0 end) NotRunnng
FROM OwnerMaster om
LEFT JOIN VehicleMaster vm ON om.OwnerID = vm.OwnerID
LEFT JOIN CustomerVehicle cv ON vm.VehicleID = cv.VehicleID
GROUP BY om.OwnerName
于 2013-10-07T20:34:59.613 回答
0

非常感谢Elhana。我已经更新了我的查询以获得我需要的确切结果。修改查询为:

    SELECT 
    om.OwnerName,
    count(vm.VehicleID) Total,
    sum(case when vm.VehicleID is not null 
        and cv.VehicleID is not null then 1 else 0 end) Runnng,
     sum(case when vm.VehicleID is not null 
        and cv.VehicleID is null then 1 else 0 end) NotRunnng
    FROM OwnerMaster om
    LEFT JOIN VehicleMaster vm ON om.OwnerID = vm.OwnerID and vm.isactive = 1
    LEFT JOIN (select distinct VehicleID from CustomerVehicle where isactive = 1) cv
    ON vm.VehicleID = cv.VehicleID
    where om.isactive = 1
    GROUP BY om.OwnerName

SQL小提琴

于 2013-10-08T07:20:31.607 回答