1

我有下面给出名称的表格

1)tblCarName
2)tblVehicle
3)tblModel
4)tblVehicleAvailability

上面三个表我已经获取了未预订车辆和特定型号的结果,然后是在特定日期车辆可用或不可用的另一条件车辆可用条件。
但我得到的结果是哪辆车不可用。(意味着那些在 tblVehicleAvailability 表中的汽车)但我想要那些不在 tblVehicleAvailability 表中的汽车)

我的查询

select 
    A.id,
    C.vsCarName+' ('+ A.EngineNum+' )' as vsCarName   
from tblCarName C 
join tblVehicle A on C.id = A.CarId
inner join tblModel B on A.ModelId = B.id 

--join tblVehicleAvailability VA on  VA.CarId = A.id

WHERE A.id not in 
(
    SELECT 
        VehicleId 
    FROM 
        tblBooking
    WHERE 
        A.ActiveInactive = 1
    AND 
        Convert(datetime,'2013-09-19 00:00:00.000') --start date
            BETWEEN FromDateWithStartTime AND ToDateWithEndTime
    OR 
        Convert(datetime,'2013-09-20 00:00:00.000')  --endDate
            BETWEEN FromDateWithStartTime AND ToDateWithEndTime
    OR 
        FromDateWithStartTime 
            BETWEEN Convert(datetime,'2013-09-19 00:00:00.000') --startdate  
          AND Convert(datetime,'2013-09-20 00:00:00.000')  --enddate  
    OR 
        ToDateWithEndTime 
            BETWEEN Convert(datetime,'2013-09-19 00:00:00.000')--start date  
            AND Convert(datetime,'2013-09-20 00:00:00.000')--enddate
) 
AND  
    A.ModelId='3' 
AND   
    Convert(datetime,'2013-09-19 00:00:00.000')  --start date  
    BETWEEN VA.leaveDate AND VA.leaveToDate  
OR 
    Convert(datetime,'2013-09-20 00:00:00.000') --endDate  
    BETWEEN VA.leaveDate AND VA.leaveToDate  
OR 
    VA.leaveDate 
    BETWEEN Convert(datetime,'2013-09-19 00:00:00.000') --startdate  
    AND Convert(datetime,'2013-09-20 00:00:00.000')  --enddate  
OR 
    VA.leaveToDate
    BETWEEN Convert(datetime,'2013-09-19 00:00:00.000') --start date
    AND Convert(datetime,'2013-09-20 00:00:00.000')
4

2 回答 2

1

试试这个:

select A.id ,C.vsCarName+' ('+ A.EngineNum+' )' as vsCarName   
from tblCarName C 
inner join tblVehicle A on C.id=A.CarId
inner join tblModel B on A.ModelId=B.id 
where not exists (
    select null from tblBooking
    where A.id = VehicleId and
    A.ActiveInactive = 1 and 
    '20130919' <= ToDateWithEndTime 
    and '20130920' >= FromDateWithStartTime
    ) 
and  A.ModelId='3' AND
'20130919' <= VA.leaveToDate  
and '20130920' >= VA.leaveDate
于 2013-09-19T12:26:34.587 回答
0

通常当我看到“OR”语句时,我开始添加 (),这样我就得到了我想要的。

编辑:但您可能还想看看使用 LEFT JOIN tblVehicleAvailability

和一个附加的 where 子句:

其中 CarID 为 NULL

最好的问候,亨里克

于 2013-09-19T12:01:55.350 回答