SQL-使用JOINS从三个表中获取值

时间:2013-10-07 19:18:03

标签: sql linq

我在项目中使用了四个表,即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

任何帮助将不胜感激。 谢谢,

3 个答案:

答案 0 :(得分: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

An SQLfiddle to test with

答案 1 :(得分: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

答案 2 :(得分: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 Fiddle