SQL SERVER 2008最终选择命令与存储过程

时间:2012-09-13 10:32:39

标签: database sql-server-2008 datetime stored-procedures

我认为正确完成它是微不足道的。

在每个用户(userid)下面的屏幕截图中有两个结果(这是一种重复)

如何修复查询以获得每个用户只有一个结果

(每个用户可以有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

1 个答案:

答案 0 :(得分:0)

不知道如何,我没有参加sql server&数据库,但这是我的最终代码 非常灵活的过滤

    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