SQL Date less than few days from today - sql

I have a table in which I have emails to users and I want to make request to take users who are dated less than two days from today. How can make this?
This is my SQL table :
CREATE TABLE vacation_users(EMAIL VARCHAR(255), STARTDATE DATE, ENDDATE DATE);

The answer is this. I use HSQLDB and this is answer.
SELECT * FROM vacation_user WHERE (ENDDATE < (SYSDATE + 2 DAY));

Try this(not tested):
SELECT EMAIL from vacation_users
WHERE ENDDATE < DATEADD(day, +2, CURRENT_DATE) AND ENDDATE > CURRENT_DATE
It selects the mails, which have the enddate, which is equal bigger than current date, but smaller than current date + 2.
EDIT: I updated the answer, since the OP informed me about the DB, which is used. If CURRENT_DATE also doesn't work, you can try another from the built-in functions.

select *
from vacation_users
where STARTDATE = dateadd(day,datediff(day,2,STARTDATE),0)

That depends on a database you use, but the principle is more or less the same.
In Oracle, you'd do something like
select email
from vacation_users
where startdate < sysdate - 2;
which returns you to exact time 2 days ago (if it is 09:53 today, it'll be 09:53 2 days ago). Depending on what you really need, you might need to TRUNCate those values (so that you'd get date without its time component) or apply some other function or principle, regarding possible index impact etc.
Though, "dated less than two days from today" is ... what exactly? Is it a STARTDATE or ENDDATE (or some combination of those two)?

SELECT *
FROM vacation_users
WHERE (DATEADD(day,2,ENDDATE)) < (CONVERT(date, SYSDATETIME()))

Related

T-SQL: How to get all records prior to the first day of the current month?

Using SQL Server: I am trying to find all records prior to the first day of the current month and set this as a parameter in an SSRS report (so I can't use a static value).
So, I need all records prior to the first day of the each current month going forward in column CREATEDDATETIME ('yyyy-mm-dd').
I have seen a lot of threads on how to find records for a specific month and various other searches but none specifically related to the above. Interested to see if the EOMONTH function will be of use here.
Thanks for the help and advice.
Here is an expression to use EOMONTH() function with optional parameter -1.
Explanations:
DateAdd: add 1 day to expression
getdate is current date
EOMONTH is end day of a given month; however, if you put an optional integer -1, this would mean last month
Thus: first day of current month is add one day to end of day last month
SELECT DATEADD(DAY,1,EOMONTH(getdate(),-1));
Result: 2018-04-01
SO in your query:
select *
from table
where CREATEDDATETIME < DATEADD(DAY,1,EOMONTH(getdate(),-1));
I would use datefromparts():
select t.*
from t
where CREATEDDATETIME < datefromparts(year(getdate()), month(getdate()), 1);
There's already two other answers that work, but for completeness here is a third common technique:
SELECT *
FROM [table]
WHERE CREATEDDATETIME < dateadd(month, datediff(month,0, current_timestamp), 0)
You might also get answers suggesting you build the date using strings. Don't do that. It's both the least efficient and most error prone option you could use.
all three answers are great, how ever you may find that it will select all the data prior to the 1st day of the current month until the 1st Createdate. This could cause the report to take forever to run, Maybe building in a limitation to the code I would use something like this to build a report that gives details for last month only.
Select [columns]
from [source]
where [Createdate] between
/*First day of last Month*/
DATEADD(mm, DATEDIFF(mm, 0, Getdate())-1, 0 and
/*First day of this Month*/
dateadd(mm,datediff(mm,0,Getdate()),0)

Retrieve upcoming birthdays in Postgres

I have a users table with a dob (date of birth) field, in a postgres database.
I want to write a query that will retrieve the next five upcoming birthdays. I think the following needs to be considered -
Sorting by date of birth won't work because the years can be different.
You want the result to be sorted by date/month, but starting from today. So, for example, yesterday's date would be the last row.
Ideally, I would like to do this without functions. Not a deal breaker though.
Similar questions have been asked on SO, but most don't even have an accepted answer. Thank you.
Well, this got downvoted a lot. But I'll post my answer anyway. One of the answers helped me arrive at the final solution, and that answer has been deleted by its owner for some reason.
Anyway, this query works perfectly. It gives the next 5 upcoming birthdays, along with the dates.
SELECT id, name,
CASE
WHEN dob2 < current_date THEN dob2 + interval '1 year'
ELSE dob2
END
AS birthday
FROM people,
make_date(extract(year from current_date)::int, extract(month from dob)::int, extract(day from dob)::int) as dob2
WHERE is_active = true
ORDER BY birthday
LIMIT 5;
You can look at day of year of dob and compare against current date's doy:
SELECT doy
, extract(doy from dob) - extract(doy from current_date) as upcoming_bday
FROM users
WHERE extract(doy from dob) - extract(doy from current_date) >= 0
order by 2
limit 5

Oracle SQL - Return records where date1 is within 24 months of date2

I'm quite new to SQL but I've been asked to write something I don't fully understand. I'm looking to select records where a date is within 24 months of another date. Something like :-
select *
from table
where (date1 within 24 months of date2)
So for example, if date1 was 01/01/2010, where date2 has the following values the corresponding records in the table would be returned:-
05/09/2009
01/02/2008
06/03/2011
but where date2 is, for example, 25/12/2013, the corresponding data in the table would not be returned.
It sounds like you want
SELECT *
FROM table
WHERE date1 >= add_months( date2, -24 )
AND date1 <= add_months( date2, 24 )
Your sample data isn't clear as to whether you want to include dates that are exactly 24 months earlier or later or not-- you can obviously adjust the <= and >= to be < and > if you want to omit dates that are exactly 24 hours apart.
An Oracle DATE column always has both a day an a time component. The query I posted will compare dates including whatever time is present. If you want to set all the time components to midnight, you can use the trunc function (i.e. trunc(date1) and trunc(date2)). If you trunc(date1) in the predicate, however, you won't be able to use an index on date1 in your query. You could create a function-based index on trunc(date1) instead, however.
An alternative to the add_months method:
select *
from table
where abs(months_between(date1, date2)) <= 24

SQL Query to Count Number of Days, Excluding Holidays/Weekends

I have a "workDate" field and a "receivedDate" field in table "tblExceptions." I need to count the number of days beteen the two. workDate always comes first - so, in effect, it's kind of like workDate is "begin date" and receivedDate is "end date". Some exclusions make it tricky to me though:
First, I need to exclude holidays. i do have a table called "tblHolidays", with one field - holidayDate. I have holidays stored up through next year, so maybe I can incorporate that into the query?
Also, most flummoxing is that work dates can never occur on weekends, but received dates can. So, i somehow need to exclude weekends when i'm counting, but allow for a weekend if the received date happens to fall on a saturday or sunday. so, if the work date is June 3rd, 2011, and received date is June 11th, 2011, the count of valid days would be 7, not 9.
Any help on this is much appreciated. Thanks!
Something like this should give you the number of days with the holidays subtracted:
select
days = datediff(day, workDate, receivedDate)
- (select count(*) from tblHolidays where holidayDate >= workDate and holidayDate < receivedDate)
from
tblExceptions
Note that the date functions differ between database systems. This is based on MS SQL Server, so it may need adapting if you are using some other database.
If you have a table full of dates to include (non-weekends, non-holidays, etc.) and you knew when the 'begin' date and the 'end' date is, then you can do something roughly like this:
select count(*) from tblIncludedDates where beginDateValue <= dateField and endDateValue >= dateField
to get the number of valid days between those dates.

SQL Select data by this week

Hi how do I get the data by current week?
Select * from Transaction where transactionDate ....
In SQL Server based on week of year. Please see DATEPART for ##DATEFIRST etc. for example, this is all trades since Sunday in US/UK settigs:
WHERE DATEPART(week, transactionDate) = DATEPART(week, GETDATE())
Edit:
For Access, use this DatePart and use "ww" for the part of date you want.
In answer to the comment, "week" is not a variable; it's the bit of the date you want
So:
WHERE DatePart("ww", transactionDate) = DatePart("ww", GETDATE())
In Microsoft Access
Last n days:
SELECT *
FROM Transaction
WHERE transactionDate >=Date()-7
If you have indexes and this type of difference suits, it will be faster because it is sargable
This week by week difference:
SELECT *
FROM Transaction
WHERE DateDiff("w",[transactionDate],Date())=0
BTW It is considered bad practice to use *
DateDiff: http://office.microsoft.com/en-us/access/ha012288111033.aspx
Simple but portable:
SELECT *
FROM Transaction
WHERE transactionDate >= ?
AND transactionDate <= ?
Calculate the two parameters in your server-side code to whatever definition of 'week' you need.
In IBM DB2
SELECT *
FROM Transaction
WHERE transactionDate BETWEEN CURRENT TIMESTAMP - 7 days AND CURRENT TIMESTAMP;
In Access, if you want to run a query to find records that fall in the current week, use
SELECT *
FROM table
WHERE table.DateField Between (Date()-Weekday(Date())+1) And (Date()-Weekday(Date())+7);
That runs Sunday through Saturday. Use +2 and +6 instead if you want the workweek.
mySQL (standard date stamp)
SELECT *
FROM Transaction
WHERE WEEK(NOW())=WEEK(transactionDate);
mySQL (unix timestamp stamp)
SELECT *
FROM Transaction
WHERE WEEK(NOW())=WEEK(FROM_UNIXTIME(transactionDate));
Bit of a unoptimized query. Could be a more efficient way.
Note: This isn't a rolling 7 days. Just the current week of the year.
EDIT: Sorry I didn't see the ms-access tag. ignore all of this :|