Getdate between times - tsql

Sorry if this has been asked somewhere all ready but I've struggled to find the answer! I have a date time field with is a date time stamp on activity.
I need to have a query that only brings back information for data that's between today's date and events between 08:00 and 10:00.My brains says it should be straight forward but i cant suss it.
Thanks

To get a particular point in time, I tend to use the DATEADD/DATEDIFF pattern. It can look a bit unwieldy, but performs quite nicely, and once you're used to seeing it, it becomes more readable:
SELECT * --TODO - Pick columns
FROM Activities
WHERE OccurredAt BETWEEN
DATEADD(day,DATEDIFF(day,'20010101',GETDATE()),'2001-01-01T08:00:00') AND
DATEADD(day,DATEDIFF(day,'20010101',GETDATE()),'2001-01-01T10:00:00')
Here I'm using it twice. It just relies on the relationship between two date constants that you pick because they exhibit the features that you want. So here:
DATEADD(day,DATEDIFF(day,'20010101',GETDATE()),'2001-01-01T08:00:00')
I'm calculating the number of (whole) days that have elapsed between 1st January 2001 and right now. I'm then adding that (whole) number of days onto 08:00 on the 1st January 2001 - which will, logically, produce 08:00 today.

Here you go...
SELECT * FROM <TABLE_NAME> WHERE EVENTS_DATE BETWEEN
DATEADD(hour, 8, DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0))
AND
DATEADD(hour, 10, DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0))
If you use a variable in TSQL then store today's date in that
DATEADD(day, DATEDIFF(day, 0, GETDATE())

select ...
where dateColumn between
convert(varchar(10), getdate(), 120) + 'T08:00:00'
and convert(varchar(10), getdate(), 120) + 'T10:00:00'

Related

TSQL datediff returning same result for week and days

Why is the datediff for the week and day returning the same results for week and day?
This is the query I am using;
select DATEDIFF("D",[ARRS-DATE], GETDATE()) daysdiff ,DATEDIFF("W",[ARRS-DATE], GETDATE()) weeksdiff,* from [RE-ARRS-HIST]
Any ideas on what can be causing this?
Thanks in advance.
"w" is not shorthand for weeks, it is an alias for WEEKDAY. Since Weekday does not really make sense as a datediff option, I would guess that this is treated like days under the hood.
If you want weeks difference, you need to use "ww" or "wk". Or better still use the full version WEEK, it is much more clear, and is not much harder to write at all.
SELECT DATEDIFF(DAY, [ARRS-DATE], GETDATE()) AS daysdiff,
DATEDIFF(WEEK, [ARRS-DATE], GETDATE()) AS weeksdiff
FROM [RE-ARRS-HIST];
Bad Habits to Kick : Using shorthand with date/time operations

T-SQL get average based off same date last 4 weeks

I have a table with results for everyday of the week for the past year. I need to get the average sales based off same day of the week(starting today) for the past 4 weeks. i.e. sales for every monday for the past 4 weeks.
What would be the best route? Any and all advice is greatly appreciated.
Fairly straight forward, the only gotcha could be performance, which is why I'm isolating the the 28 day function so the cutoff date can be a SARG.
declare #cutoffdate datetime = dateadd(day, -28, (DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0)))
select avg(sales) as averagesales
, datepart(dw, saledate) as saleDayOfWeeks
from your table
where saledate >= #cutoffdate
group by datepart(dw, saledate)
Let me know if that doesn't work.

Get this week's monday's date in Postgres?

How can I get this week's monday's date in PostgreSQL?
For example, today is 01/16/15 (Friday). This week's monday date is 01/12/15.
You can use date_trunc() for this:
select date_trunc('week', current_date);
More details in the manual:
http://www.postgresql.org/docs/current/static/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC
If "today" is Monday it will return today's date.
SELECT current_date + cast(abs(extract(dow FROM current_date) - 7) + 1 AS int);
works, although there might be more elegant ways of doing it.
The general idea is to get the current day of the week, dow, subtract 7, and take the abs, which will give you the number of days till the end of the week, and add 1, to get to Monday. This gives you next Monday.
EDIT: having completely misread the question, to get the prior Monday, is much simpler:
SELECT current_date - ((6 + cast(extract(dow FROM current_date) AS int)) % 7)
ie, subtract the current day of the week from today's date (the number of day's past Monday) and add one, to get back to Monday.
And for other mondays:
Next Monday:
date_trunc('week', now())+ INTERVAL '7days'
Last week's monday:
date_trunc('week', now())- INTERVAL '7days'
etc. :)
I usually use a calendar table. There are two main advantages.
Simple. Junior devs can query it correctly with little training.
Obvious. Correct queries are obviously correct.
Assuming that "this week's Monday" means the Monday before today, unless today is Monday then . . .
select max(cal_date) as previous_monday
from calendar
where day_of_week = 'Mon'
and cal_date <= current_date;

First Day of Next Year for SQL Server?

This should not be this hard. I simply need the following:
SET #DueDate = CONVERT (DATETIME, '01/01/2010')
However, I need it pragmatically so that if it were March of 2010, the date given would be '01/01/2011'.
I know it's simple, but my brain isn't coming up with it. I'm sure it's with a DateAdd and getdate().
Number of year boundaries between now and year zero less one (31 dec 1899), add back on.
SELECT DATEADD(year, DATEDIFF(year, -1, GETDATE()), 0)
Let's try a date next year to get 2011. because 1 Jan 2010 is start of next year in 2009...
SELECT DATEADD(year, DATEDIFF(year, -1, '2010-03-21'), 0)
Based on the Database Journal article: How to Calculate Different SQL Server Dates:
First Day of the Next Year
I use the year interval (yy) to display the first day of the next year.
select DATEADD(yy, DATEDIFF(yy, -1, getdate()), 0)
Incidentally, with SQL 2012 you can do DATEFROMPARTS(YEAR(#date) + 1, 1, 1). In your case, DATEFROMPARTS(YEAR(GETDATE()) + 1, 1, 1)
Hat tip to https://stackoverflow.com/a/13873750/155892
Perhaps, create a table with first of the year dates, then pick the smallest that is larger than your date.
Perhaps simply put a string together, '01/01' + (MyYear + 1)?
You could add one to the current year, then concat with Jan 01, then convert back to date:
select CONVERT(datetime, CONVERT(VARCHAR(20), YEAR(GETDATE())+1) + '.01.01')
Using some parts of the examples above you could also do this. Now this assumes your acceptable date format matches M-d-yyyy.
DATEADD(year, 1,'1-1-'+convert(varchar,DATEPART(YYYY,GetDate())))
Note: You get the current date, get the year part, create a string that converts to a date, then add one to the year.

How do I do a running year for a calendar report?

Here is the Query I am using:
SELECT * FROM ra_ProjectCalendar
WHERE MonthNumber between #Month and #Month + 12 and FullYear = #Year
It works great for this year, but, stops at December of this year. How do I get it to show a running year?
how is your date stored?
from your sql, i guess that you have one field for month, one for year and one for day. i'd recommend having one single datetime field instead, and then you can use the DateAdd() method to add 12 months (or any other interval).
EDIT: it was pointed out to me in a comment that one thing you gain on this is performance - which is more or less important depending on the scale of your applicaiton, but always nice to be aware of. if you run this query in a stored procedure, here's what you'll do:
DECLARE #oneYearAhead datetime;
SET #oneYearAhead = DateAdd(m, 12, #PassedDate)
SELECT * FROM ra_ProjectCalendar
WHERE #PassedDate <= [Date] AND [Date] <= #oneYearAhead;
with the above code, you will get all entries between the date you pass, and one year ahead of it. (i am not 100% sure on the syntax to declare and set the #oneYearAhead variable, but you get the idea...). Note that the [] that i use around the column name Date allows me to use reserved words in column names - i have made it a habit, instead of memorizing which words are reserved...
Try this:
SELECT * FROM ra_ProjectCalendar
WHERE
(MonthNumber > #Month AND FullYear = #Year)
OR (MonthNumber < #Month AND FullYear = #Year + 1)
Something like this might work better - but its not clear what your intent is:
select *
from ra_ProjectCalendar
where DATEDIFF ( month , #startdate , #enddate ) <=12
Edit: This is SQl server syntax
Actually pass in and store the date rather than month and year, and compare with the current date using DateDiff:
WHERE DATEDIFF(m, #PassedDate, StoredDateColumn) < 12
Note that I used 12 months, rather than 1 year, because DATEDIFF counts the number of boundries crossed. So in december, using datediff with the year datepart would return one after only one month. You really want a 12 month span.
Depending on how your information is stored (it's a little difficult to tell from your query), either DATEADD or DATEDIFF will probably do you right. There's a list of the availabe date functions on MSDN.