0

我想把它做好是微不足道的。

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

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

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

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

在此处输入图像描述

这是存储过程

    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
4

1 回答 1

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
于 2012-09-13T23:09:55.820 回答