2012-09-13 52 views
0

我认为将它正确完成是微不足道的。带有存储过程的SQL SERVER 2008最终选择命令

在屏幕截图下面的每个用户(用户ID)

有两个结果(这是一种重复的)

如何解决查询来获取每个用户

(每个用户只有一个结果可以有2组“TimeIn”和“TimeOut”活动)

所以如果给定的用户确实有第二个“入口”,但没有离开 我只需要第一个封闭的入口/离开+第二个入口/仍然工作

enter image description here

这里是存储过程

create table #tmp (tId int, UserId int, 
    TimeIn1 smalldatetime, [TimeOut1] smalldatetime, 
    TimeIn2 smalldatetime, [TimeOut2] smalldatetime, tId2 int, 
    ActiveDate smalldatetime, ReasonID int, Name nvarchar(100), ReasonType nvarchar(100), 
    TotalMins int) 

    insert into #tmp (tId, UserId, TimeIn1, TimeOut1, ActiveDate, ReasonID, Name, ReasonType) 
    SELECT 
    t1.tId, t1.UserId, t1.TimeIn, t1.[TimeOut], t1.ActiveDate, t1.ReasonID, tblCustomers.name,tblTimeReas.ReasonType 
    FROM tblTime t1 
    inner join tblTimeReas on t1.ReasonID = tblTimeReas.ReasonID 
    inner join tblCustomers on t1.UserId=tblCustomers.custID 
    where (t1.userid in (select custID from tblCustomers where Classification =35)) 
    and (DATEPART(DAY,t1.timein)= DATEPART(DAY,GETDATE())) 
    and (DATEPART(MONTH,t1.timein)= DATEPART(MONTH,GETDATE())) 
    and (DATEPART(YEAR,t1.timein)= DATEPART(YEAR,GETDATE())) 

    update #tmp 
    set tId2 = (select top 1 tId from 
    tblTime t2 where (userid in (select custID from tblCustomers where Classification =35)) and DATEDIFF(day,t2.timein,#tmp.timein1)=0 
        and t2.tId>#tmp.tId order by tId asc) 


    update #tmp 
    set TimeIn2 = (select TimeIn from tblTime where tId=tId2), 
     TimeOut2 = (select [TimeOut] from tblTime where tId=tId2) 


    update #tmp set TotalMins = (
     isnull(DATEDIFF(minute,timein1,timeout1),0)+ 
     isnull(DATEDIFF(minute,timein2,timeout2),0) 

    ) 

    select * from #tmp order by TimeIn1 
    drop table #tmp 

回答

0

不知道我是怎么,不采取为SQL Server & DATABSE一门课程,但是这是我 多flexable过滤

create table #tmp (tId int, UserId int, 
    TimeIn1 smalldatetime, [TimeOut1] smalldatetime, 
    ActiveDate smalldatetime, ReasonID int, Name nvarchar(100), ReasonType nvarchar(100), 
    TotalMins int) 

    insert into #tmp (tId, UserId, TimeIn1, TimeOut1, ActiveDate, ReasonID, Name, ReasonType) 
    SELECT 
    t1.tId, t1.UserId, t1.TimeIn, t1.[TimeOut], t1.ActiveDate, t1.ReasonID, tblCustomers.name,tblTimeReas.ReasonType 
    FROM tblTime t1 
    inner join tblTimeReas on t1.ReasonID = tblTimeReas.ReasonID 
    inner join tblCustomers on t1.UserId=tblCustomers.custID 
    where (t1.userid in (select custID from tblCustomers where Classification Like '%,35%')) 
    and (DATEPART(DAY,t1.timein)= DATEPART(DAY,GETDATE())) 
    and (DATEPART(MONTH,t1.timein)= DATEPART(MONTH,GETDATE())) 
    and (DATEPART(YEAR,t1.timein)= DATEPART(YEAR,GETDATE())) 
    and TimeOut is null 


    update #tmp set TotalMins = (
     isnull(DATEDIFF(minute,timein1,GETDATE()),0) 
    ) 

    select *from #tmp order by TimeIn1 
    drop table #tmp 
最终代码