Sql Query information - sql

What does this do in a SQL Query? Can someone explain? What does the .5- represent?
WHERE ScheduleEntry.ScheduleDate >= getdate() and ScheduleEntry.ScheduleDate <= getDate() +.50

Think of date unit as 1 day. 0.50 of a day is 1/2 of a day. So this returns anything that has ScheduleDate within half a day from getdate() time forward.

It restricts the rows returned to rows where the ScheduleEntry.ScheduleDate is in the future and where it is not more than .50 units later than the current date. To find out how much time .50 units is equal to, run the following on your console:
SELECT getDate()
SELECT getDate() +.50
The difference between the dates should tell you the difference. Most likely, it is half a day.

GETDATE returns the current date and time in SQL.
You can use addition to "add days" to the current date.
Generally, it is better to use DATE_ADD instead of adding directly and is probably easier to read. Adding 0.5 is akin to adding half a day (or 12 hours).

To better illustrate, the .5 is half a day
SELECT DateDiff(HH,getDate(),getDate() +.50)
Returns 12 hours

Related

sql statement - would like to subtract 1 date from another and get the days hours and mins inbetween

I would like to subtract 1 date from another and get the days hours and mins in-between.
I know there is a DateDiff function, however it does not work with all 3 time values; days hours and mins. I would like this doable in an SQL statement. Currently I have the following.
SELECT id, pickupdateandtime, GETDATE() AS CurrentTime,
(DATEDIFF(day,GETDATE(),pickupdateandtime)) AS Days,
(DATEDIFF(hour,GETDATE(),pickupdateandtime)) AS Hours,
(DATEDIFF(minute,GETDATE(),pickupdateandtime)) AS Mins FROM orders
And it shows up like this:
If we can stick it all in 1 column that's fine too.
I agree with #AndyMcLaughlin about the use of the mod operator % here. It's very handy for this sort of thing. However, I have a general distrust of DATEDIFF. That function does not count the whole number of years (say) between two dates, but the number of year boundaries between them.
So DATEDIFF "thinks" the difference in years between 01-Jan-2000 and 01-Jan-2001 is the same as that between 31-Dec-2000 and 01-Jan-2001.
This is why #Michael saw a need to subtract 1 from #AndyMcLaughlin's results. Unfortunately, that doesn't always work, it will depend on the individual case.
As a rule, DATEDIFF works well when it's used against the smallest interval you are interested in. So if you are interested in years and simply want to separate one calendar year from another, it'll serve you well.
I think the smallest interval we are interested in here is minutes. So we can use DATEDIFF for that, but have to work upwards from there to hours and days:
select
mf.id,
mf.pickupdateandtime,
mf.CurrentTime,
--The divisions in the following lines simply
--truncate since all the numbers are integers
--but that works in our favour here
(mf.MinutesFull/(60*24)) as Days,
(mf.MinutesFull/60) % 24 as Hours,
mf.MinutesFull % 60 as Minutes
from
(
select
id,
pickupdateandtime,
getdate() as CurrentTime,
datediff(minute, getdate(), pickupdateandtime) as MinutesFull
from #orders
) mf
You need to use the mod operator % to remove whole days from hours and whole hours from minutes.
So you can do something like:
SELECT
id,
pickupdateandtime,
GETDATE() AS CurrentTime,
(DATEDIFF(day,GETDATE(),pickupdateandtime)) AS Days,
(DATEDIFF(hour,GETDATE(),pickupdateandtime) % 24) AS Hours,
(DATEDIFF(minute,GETDATE(),pickupdateandtime) % 60) AS Mins FROM orders

DATEDIFF - How many days until Sunday

In SQL Server, trying to write a age-off report for inventory purposes. Each week, the inventory system marks thousands of rows for deletion. This takes place on Sundays # 06:00:00 as part of weekly SQL DB purge schedule.
Using (yyyy-mm-dd hh:mm:ss:ms) format for closed_time, how can I calculate the numbers of days between that date, until next Sunday of the current week? And to be more elaborate, is there a way to narrow it down to the exact DD:HH:MM? The problem is the each client's Sunday DB schedule for purge varies. So that might be difficult to compute. Might be easier to just calculate whole days until Sunday 00:00:00. I tried using the DATEDIFF function with no success.
SELECT
Yada
DATEDIFF(DAY, closed_time,DW) AS Days_Until_Purged
FROM DB1
WHERE closed_time DESC
Thx in advance
If you choose any Sunday in the past (Such as 06:00 Sunday 2nd January 2000), you can calculate time that has GONE BY since then.
Then, if you take that and do modulo 7-days you get the time that has gone by since the most recent Sunday.
Then, if you do 7 - time_gone_by_since_last_sunday you get the time until the next sunday.
I'm going to do this in minutes to cope with a client that has a setting of 06:30.
DECLARE
#batch_processing_time SMALLDATETIME
SET
#batch_processing_time = '2000-01-02 06:00'
SELECT
(60*24*7) - DATEDIFF(minute, #batch_processing_time, closed_time) % (60*24*7)
FROM
yourTable
That's the number of minutes from each record's closed_time until the next #batch_processing_time.
Divide by (24*60) to get it in days.
try this:
select 8-DATEpart(w, closed_time) AS Days_Until_Purged from DB1 ...
This should solve your problem
SET DATEFIRST 1
Select DATEDIFF(dd,GETDATE(),DATEADD(DAY , 7-DATEPART(WEEKDAY,GETDATE()),GETDATE()))

SQL WHERE timestamp BETWEEN MIDNIGHT AND MIDNIGHT

For my website I must select all messages sent between midnight (the previous night) and midnight (the next night). Basically, it's a 24 hours range.
I don't know how to do that as I store the date in a timestamp format in my DB.For example, last message was posted on 2013-10-18 11:23:35.
What I want is all message posted between 2013-10-18 00:00:00 and 2013-10-18 23:59:59.
Is that possible, if yes, how could I do that ?
You can calculate the required time in T-SQL as :
-- for previous day mid night as start time
declare #start_datetime datetime,#end_datetime datetime
Select #start_datetime = DATEADD(d,0,DATEDIFF(d,0,GETDATE()))
-- for current day mid night as end time
Select #end_datetime = DATEADD(SS,86399,DATEDIFF(d,0,GETDATE()))
select #start_datetime, #end_datetime
and then use you column name to check whether it exists between these two values.
To find out what happened between DatetimeA and DatetimeB, the sql keyword between is not your friend. It generally causes one to miss records. This construct is better.
where YourDateTimeField >= StartDateTime
and YourDateTimeField < JustAfterTheEndDateTime
In your case, you can simplify it with
where YourDateTimeField >= DateA
and YourDateTimeField < TheDayAfterDateA

How to subtract 1 minute from hour

I have a query contains from time and to time parameters.
I need to subtract 1 minute from totime parameter.
I used totime-1.
It is working in database level and it is not working in my crystal reports.I mean it is subtracting 1 hour in report level.
Can any one please tell me other formula for subtracting a minute.
Thanks,
vissu
If you are using SQL Serve/T-sql
DATEADD(MI, -1, totime)
In some databases (SQL Server and Oracle for instance), you can do the following:
select totime - 1.0/(24*60)
Time differences are measured in days, so 1.0/(24*60) is one minute represented as a fraction of a day.
MySQL accepts the syntax, but the timestamp is measured in seconds not days, so you would use:
select totime - 60

Battling Datediff in SQL

I am writing a little query in SQL and am butting heads with an issue that it seems like someone must have run into before. I am trying to find the number of months between two dates. I am using an expression like ...
DATEDIFF(m,{firstdate},{seconddate})
However I notice that this function is tallying the times the date crosses the monthly threshold. In example...
DATEDIFF(m,3/31/2011,4/1/2011) will yield 1
DATEDIFF(m,4/1/2011,4/30/2011) will yield 0
DATEDIFF(m,3/1/2011,4/30/2011) will yield 1
Does anyone know how to find the months between two dates more-so based upon time passed then times passed the monthly threshold?
If you want to find some notional number of months, why not find the difference in days, then divide by 30 (cast to FLOAT as required). Or 30.5-ish perhaps - depends on how you want to handle the variable month length throughout the year. But perhaps that's not a factor in your particular case.
The following statements have the same startdate and the same endate. Those dates are adjacent and differ in time by .0000001 second. The difference between the startdate and endate in each statement crosses one calendar or time boundary of its datepart. Each statement returns 1. ...
SELECT DATEDIFF(month, '2005-12-31 23:59:59.9999999'
, '2006-01-01 00:00:00.0000000'); ....
(from DATEDIFF, section datepart Boundaries ). If you are not satisfied by it, you probably need to use days as unit as proposed by martin clayton
DATEDIFF(m,{firstdate},ISNULL({seconddate},GETDATE())) - CASE
WHEN DATEPART(d,{firstdate}) >= DATEPART(d,ISNULL({seconddate},GETDATE()))
THEN 1
ELSE 0
DATEDIFF is like this by design. When evaluating a particular time measurement (like months, or days, etc.), it considers only that measurement and higher values -- ignoring smaller ones. You'll run into this behavior with any time measurement. For example, if you used DATEDIFF to calculate days, and had one date a few seconds before midnight, and another date a few seconds after midnight, you'd get a "1" day difference, even though the two dates were only a few seconds apart.
DATEDIFF is meant to give a rough answer to questions, like this:
Question: how many years old are you?
Answer: some integer. You don't say "I'm 59 years, 4 months, 17 days, 5 hours, 35 minutes and 27 seconds old". You just say "I'm 59 years old". That's DATEDIFF's approach too.
If you want an answer that's tailored to some contextual meaning (like your son who says "I'm not 8! I'm 8 and 3-quarters!, or I'm almost 9!), then you should look at the next-smallest measurement and approximate with it. So if it's months you're after, then do a DATEDIFF on days or hours instead, and try to approximate months however it seems most relevant to your situation (maybe you want answers like 1-1/2 months, or 1.2 months, etc.) using CASE / IF-THEN kinds of logic.