• WOW!!!! Your second post and you nailed the ddl and sample data. Excellent job!!! This takes many people dozens of posts, if they ever actually do it right. The only minor change was I had to remove the ID from the column list on the insert. Having ddl and sample data makes helping so much easier. Thank you for that.

    It would be nice if I knew what you expected as output based on your sample data but in this case the result set is small enough it isn't too bad. I think this should get you what you are looking for.

    select i.EmpID, i.Htime as InTime, o.Htime as OutTime, DATEDIFF(minute, i.Htime, o.Htime) as MinutesSpent

    from tblEMPLog i

    outer apply

    (

    select top 1 *

    from tblEMPLog OutPunches

    where OutPunches.EmpID = i.EmpID

    and Status = 'Out'

    and OutPunches.Htime > i.Htime

    order by Htime

    ) o

    where i.Status = 'In'

    This will return rows when there is no matching 'Out' punch. If you want to eliminate those you can just change the outer apply to a cross apply.

    _______________________________________________________________

    Need help? Help us help you.

    Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.

    Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.

    Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
    Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
    Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
    Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/