带条件的SQL Server查询

时间:2013-08-29 05:06:33

标签: sql sql-server database

我有四张桌子。

  1. 驾驶员出勤
  2. 驱动程序信息
  3. Vechile Detail
  4. 预订明细
  5. 我想根据某些条件写一个查询。

    每当驱动程序绑定时,它将根据分配给驱动程序的车辆进行绑定。并且只有该驱动程序将进入下拉列表,这不是每周关闭,他们不会在我将发送的特定日期休假。

    • tblDriverInformation列是:1)id 2)每周关闭

    • tblDriverAttendance列是---> 1)辫子2)离开日期3)离开日期

    • Driver Id在上表中很常见。

    • tblVehicle列是---> 1)分配给>驱动程序(在上表中很常见)2)id

    • tblBooking列是---> 1)车辆ID 2)从开始时间的日期开始3)结束日期与时间tblVehicletblBooking(在两个表中id和车辆ID是公共密钥)

    我准备了一个查询,但它没有给出正确的权利,但因为我不理解如何设置tblDriverInformationtblDriverAttendance条件。

    我的查询是:

     select 
         A.id, 
         (C.FName + '-' + C.LName) as Car_Driver 
     from 
         tblVehicle A 
     inner join  
         tblDriverInformation C on A.CarId = C.id  
     where
         A.id not in (SELECT VehicleId  
                      FROM tblBooking 
                      join tblVehicle on C.id = A.AssignedDriver 
                      WHERE A.id = @vechileid 
                       and Convert(datetime,@FromDateWithStartTime)  --start date  
                           BETWEEN FromDateWithStartTime AND ToDateWithEndTime  
                        OR Convert(datetime,@ToDateWithEndTime) --endDate  
                           BETWEEN FromDateWithStartTime AND ToDateWithEndTime  
                        or FromDateWithStartTime 
                           BETWEEN Convert(datetime,@FromDateWithStartTime) -- startdate  
                                   AND Convert(datetime,@ToDateWithEndTime)  -- enddate  
                        or ToDateWithEndTime 
                           BETWEEN Convert(datetime,@FromDateWithStartTime) -- start date  
                           AND Convert(datetime,@ToDateWithEndTime)   -- enddate
    

1 个答案:

答案 0 :(得分:0)

这可能会帮助您,在查询下方查找与以下条件相关的车辆和驾驶员。

1-司机不是每周休息。

2-在指定日期提供的车辆(即尚未预订)

3-在指定日期可用的驱动程序(即尚未预订)

SELECT D.ID, V.id
    FROM tblDriverInformation D
    INNER JOIN tblVehicle ON V.DRIVER_ID = D.DRIVER_ID
    INNER JOIN tblDriverAttendance tda ON  tda.DRIVER_ID = D.DRIVER_ID 
    INNER JOIN tblBooking tbl ON V.ID = tbl.VECHILCE_ID 
    WHERE D.WEEKLY_OFF= FALSE -- Driver Not Absent
    AND (@DRIVER_FROM_DATE  NOT BETWEEN (tda.FROMDATE,tda.TODATE) OR @DRIVER_TO_DATE NOT BETWEEN (tda.FROMDATE,tda.TODATE)) -- Driver not absent in these dates
    AND (@VEHILE_FROM_DATE  NOT BETWEEN (tbl.FROMDATE,tbl.TODATE) OR @VEHILE_TO_DATE NOT BETWEEN (tbl.FROMDATE,tbl.TODATE)) -- vehicle not booked in these dates
    -- @DRIVER_FROM_DATE , @DRIVER_TO_DATE, @VEHILE_FROM_DATE, @VEHILE_TO_DATE( user input selected date )