Click here to Skip to main content
15,886,110 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a db table (MS SQL) that contains in and out registrations for an office.
cardnumber, timestamp, in|out

I would like to know what card numbers that currently are in the office.

Is it possible to construct a SQL query that can pick out the cardnumbers that has checked in but not out (after they checked in) for the last 24 hours?

What I have tried:

I can of course loop through all the records and pick out checkins without a checkout, but it causes a lot of looping. It would be nice to find a SQL query that does it instead.
Posted
Updated 4-May-22 5:06am

1 solution

Seems simple enough, assuming you've used sensible data-types for your columns:
SQL
DECLARE @Now datetime2(0) = GetDate();
DECLARE @MinDate datetime2(0) = DateAdd(day, -1, @Now);

SELECT
    CardNumber,
    Timestamp
FROM
    YourTable As I
WHERE
    I.InOut = 'in'
And
    I.Timestamp >= @MinDate
And
    Not Exists
    (
        SELECT 1
        FROM YourTable As O
        WHERE O.CardNumber = I.CardNumber
        And O.InOut = 'out'
        And O.Timestamp >= I.Timestamp
    )
;
The only complication will be if your system allows an "in" and "out" at the same time for the same card number. If so, does that count as an "out" followed by an "in", or an "in" followed by an "out"?
 
Share this answer
 
Comments
Per Sehlin 4-May-22 13:12pm    
It's an elegant solution. Exactly what I was looking for.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900