2

SQL isn't my greatest strength and I need some help building a select statement.

Basically, this is my requirement. The table stores a list of names and a timestamp of when the name was entered in the table. Names may be entered multiple times during a week, but only once a day.

I want the select query to return names that were entered anytime in the past 7 days, but not today.

To get a list of names entered today, this is the statement I have:

Select * from table where Date(timestamp) = Date(now())

And to get a list of names entered in the past 7 days, not including today:

Select * from table where (Date(now())- Date(timestamp) < 7) and (date(timestamp) != date(now()))

If the first query returns a set or results, say A, and the second query returns B, how can I get

B-A

3 Answers 3

4

Try this if you're working with SQL Server:

 SELECT * FROM Table
 WHERE   Timestamp BETWEEN  
        dateadd(day,datediff(day,0,getdate()),-7), 
    AND dateadd(day,datediff(day,0,getdate()),0)

This ensures that the timestamp is between 00:00 7 days ago, and 00:00 today. Today's entries with time greater than 00:00 will not be included.

Sign up to request clarification or add additional context in comments.

3 Comments

I could be wrong but, as I read the question, the requirement is to exclude names that were entered in the previous 7 days and also entered today.
@Joe: I went back to the question as well. "...return names that were entered anytime in the past 7 days, but not today"
Joe was right in his interpretation of my question. However, when i went back to read my question, I do realized I worded it ambiguously. Sorry, and thank you for trying to help anyways.
3

In plain English, you want records from your second query where the name is not in your first query. In SQL:

Select * 
    from table 
    where (Date(now())- Date(timestamp) < 7) 
        and (date(timestamp) != date(now()))
        and name not in (Select name 
                             from table 
                             where Date(timestamp) = Date(now())
                        )

Comments

1
not in

like

select pk from B where PK not in A

or you can do something like

Select * from table where (Date(now())- Date(timestamp) < 7) and (Date(now())- Date(timestamp) > 1)

2 Comments

The following query returns all names entered from day D-1 to day D-7. But from this set of results, I still need to exclude all results that may have been entered on day D. Thank you for trying, though.
wasn't sure which way you meant. why would they want to exclude names just because they were entered today? but since they do, then you need to use NOT IN, like in Joe's example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.