简体   繁体   中英

Sql Query for Ms access database

Below is my table structure in ms access,

SNo    Time        EmpId    Date      Type
-------------------------------------------
  1   09:20:53 AM    1     9/12/2012  IN      
  2   09:50:12 AM    1     9/12/2012  OUT 
  3   09:52:09 AM    1     9/12/2012  IN
  4   12:15:10 PM    1     9/12/2012  OUT

The output should compare time and find the difference in 1st two rows and the next 2 (3rd and 4th) rows Output required is,

EmpId   Date          Time
 1     9/12/2012     0:30:41
 1     9/12/2012     2:23:01

Could Somebody kindly help please.Would really appreciate it, Thanks.

I think this query is close to what you want, assuming your Date and Time fields are both Date/Time data type. If they are actually text type, you can transform their values with CDate() . But either way, I think a query would be easier with a single field to hold both the date and time rather than separate fields for each.

SELECT
    sub.SNo,
    sub.EmpId,
    sub.Type,
    sub.start_time,
    sub.end_time,
    Format(sub.end_time - sub.start_time, 'h:nn:ss') AS duration
FROM
    (
        SELECT
            o.SNo,
            o.Date + o.Time AS end_time,
            o.EmpId,
            o.Type,
            (
                SELECT TOP 1 i.Date + i.Time
                FROM YourTable AS i
                WHERE
                        i.Type = 'IN'
                    AND i.EmpId = o.EmpId
                    AND i.Date + i.Time < o.Date + o.Time
                ORDER BY i.Date, i.Time DESC
            ) AS start_time
        FROM YourTable AS o
        WHERE o.Type='OUT'
    ) AS sub;

BTW, Date , Time and Type are reserved words and therefore not ideal choices as field names. Although those names weren't a deal-breaker for this query, you could avoid other potential headaches by renaming those fields if possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM