如何从多个表中检查多个日期

时间:2015-06-20 16:23:47

标签: sql sql-server

我试图从两个表中获取结果,一个表有数据,另一个表有时间。我的桌子看起来像这样。

CheckInOut:

USERID  int Unchecked
CHECKTIME   datetime    Unchecked
CHECKTYPE   varchar(1)  Checked

数据:

84  2015-06-16 11:15:17.000 I
84  2015-06-16 20:42:52.000 O
84  2015-06-17 11:04:43.000 I
84  2015-06-17 20:59:32.000 O
84  2015-06-18 10:35:05.000 I
84  2015-06-18 16:37:14.000 O
84  2015-06-18 16:38:56.000 O
84  2015-06-20 10:34:15.000 I

ShiftName

ShiftName StartTime EndTime
---------------------------
Morning   9:00    6:00
After     12:00   9:00

EmpShift

EmpNo  StartDate    EndDate      ShiftName
------------------------------------------
84  2015-04-01  2015-06-17  Store
191 2015-05-01  2015-06-10  Store
126 2015-04-01  2015-06-10  Store
105 2015-04-01  2015-06-10  Morning
103 2015-05-01  2015-06-30  Morning
106 2015-06-13  2015-06-18  AfterNoon
86  2015-06-01  2015-06-30  Morning
84  2015-06-18  2015-07-18  Morning

在我的案例中,empid 84在同月有两个班次。但是当我执行我的查询时,它只检查第一个。我的意思是它只返回所有行的早晨。

请检查我的查询。

Select  
    EmpShift.EmpID,
    EmpShift.ShiftName,
    EmpShift.StartDate,
    EmpShift.EndDate,
    Convert(varchar(10), CHECKINOUT.CheckTime, 121) As WorkDate,
    convert(char(5), Min(CHECKINOUT.CheckTime), 108) As CheckTime,
    CHECKINOUT.CheckType,
    CHECKINOUT.CheckTime
From    
    EmpShift
Inner Join 
    CHECKINOUT On EmpShift.EmpID = CHECKINOUT.USERID 
Where  
    ((EmpShift.EmpID = 100) AND
     ((EmpShift.StartDate Between '2015-06-01' AND '2015-06-30') AND
     (EmpShift.EndDate Between  '2015-06-01' AND '2015-06-30')))
Group By 
     EmpShift.EmpID, 
     Convert(varchar(10), CHECKINOUT.CheckTime, 121),convert(char(5), CHECKINOUT.CheckTime, 108),
     EmpShift.EmpID, EmpShift.ShiftName, 
     EmpShift.StartDate, EmpShift.EndDate,
     CHECKINOUT.CheckType, CHECKINOUT.CheckTime

1 个答案:

答案 0 :(得分:0)

我认为这就是你所追求的:

Select  EmpShift.EmpID,
            EmpShift.ShiftName,
            EmpShift.StartDate,
            EmpShift.EndDate,
            CHECKINOUT.CheckType,
            CHECKINOUT.CheckTime
    From    EmpShift
            Inner Join CHECKINOUT On EmpShift.EmpID=CHECKINOUT.USERID 
            and CHECKINOUT.CheckTime >= EmpShift.StartDate 
            and CHECKINOUT.CheckTime < EmpShift.EndDate
    Where  (--(EmpShift.EmpID=84) AND
     ((EmpShift.StartDate < '2015-06-30') AND
     (EmpShift.EndDate > '2015-06-01')))

现在,EmpShift和CHECKINOUT中的日期之间存在链接。

您可以在SQL Fiddle中对此进行测试。我创建了CHECKINOUT 6行,I和O行3天不间断