SQL查询如何获取时差Beetwen两个结果

时间:2019-01-28 04:17:47

标签: sql sql-server

我有这个T-SQL查询:

select * 
from 
    (select 
         a.ID, u.Name, 
         cast(a.time as date) as Date, 
         min(cast(a.time as time)) as Timex, 
         a.location as Location, a.state as State
     from        
         ATTENDANCE a
     join           
         EMPLOYEE u on a.id = u.id COLLATE DATABASE_DEFAULT
     group by    
         a.id, u.Name, cast(a.time as date), a.location, a.state) x 
where 
    x.Date >= '2019-01-07' 
    and x.Date <= '2019-01-07' 
    and x.Location = 'Office' 
    and x.id = '1' 
order by 
    x.Name asc, x.State asc

结果如下:

ID | Name   | Date      | Timex  | Location | State |
---+--------+-----------+--------+----------+-------+
1  |Joe     |2019-01-07 |08:00:00| Office   | In    | 
1  |Joe     |2019-01-07 |18:00:00| Office   | Out   | 

如何从该结果中获取时差?由于该查询,每个员工都有两个结果。谢谢

2 个答案:

答案 0 :(得分:2)

您可以尝试以下操作-使用条件聚合和datediff()函数

with cte as 
(
select * from (select a.ID, u.Name,cast(a.time as date) as Date ,min(cast(a.time as time)) as Timex, a.location as Location,a.state as State
            from        ATTENDANCE a
            join        EMPLOYEE u
            on          a.id = u.id
            COLLATE DATABASE_DEFAULT
            group by    a.id, u.Name, cast(a.time as date),a.location,a.state)x where x.Date>= '2019-01-07' and x.Date <= '2019-01-07' AND  x.Location ='Office' and x.id='1' order by x.Name ASC,x.State ASC
)
select id, name, date,
  datediff(hh,max(case when state='In' then timex end),
  max(case when state='Out' then timex end)) from cte
  group by id, name, date

答案 1 :(得分:1)

尝试像这样枢纽价值观

;WITH CTE
AS
(
    SELECT 
        * 
        FROM   
        (
            SELECT 
                a.Id, 
                u.[Name], 
                Cast(a.[Date] AS DATE)      AS [Date], 
                Min(Cast(a.Timex AS TIME)) AS Timex, 
                a.[Location]                AS [Location], 
                a.[State]                   AS [State] 
                FROM   attendance a 
                    JOIN employee u 
                        ON a.id = u.id COLLATE database_default 
                    GROUP  BY 
                        a.id, 
                        u.[NAME], 
                        Cast(a.[Time] AS DATE), 
                        a.[Location], 
                        a.[State]
        )x 
        WHERE  x.[Date] >= '2019-01-07' 
            AND x.[Date] <= '2019-01-07' 
            AND x.[Location] = 'Office' 
            AND x.id = '1' 
        ORDER  BY 
            x.[Name] ASC, 
            x.[State] ASC 
)
SELECT
    Id,
    [Name],
    [Date],
    [Location],
    TimeIn = DATEDIFF(hh,[In],[Out])
    FROM CTE
    PIVOT
    (
        MAX(Timex)
        FOR
        [State] IN 
        (
            [In],[Out]
        )   
    )Q