Thursday, March 29, 2012

Getting the past 24 hours worth of data?

I have a need to query my data and return only the last 24 hours (versus last day) worth of data.

My date and time fields are called:

calc_date = the date
Calc_time= the time
RealTime = Calc_date+Calc_time as realtime

I know if I use getdate()-1 that will get me the last day, but I need the last 24 hours. Any ideas on how would I do this?

I think what you're after is the DATEADD() function, so to get the start of the last 24 hours you could use:

DATEADD(hh,-24,GetDate())

e.g. SELECT DATEADD(hh,-24,GetDate()) AS [24HoursAgo]

hh = hours

|||

Hi Jim,

Follow this example, I hope it'll help you.

declare @.date nvarchar(10),

@.time nvarchar(8),

@.lastday datetime

select

@.date = '2007-07-08',

@.time = '15:45:20',

@.lastday = convert(datetime, (@.date + ' ' + @.time))

select

'Before:' as [Info],

@.date as [Date],

@.time as [Time],

@.lastday as [DateTime]

select

'After:' as [Info],

@.date as [Date],

@.time as [Time],

dateadd(hh, -24, @.lastday) as [DateTime]

|||

Actually, Jim, if you want the last 24 hours GETDATE() - 1 should work just fine. Look at this:

Code Snippet

select getdate() as now,
getdate()-1 as [24 hours ago]

/*
now 24 hours ago
-
2007-08-16 07:22:42.340 2007-08-15 07:22:42.340

|||

Your query might be like this..

Code Snippet

select

*

From

<Table Name>

Where

Cast(Calc_date+Calc_timeas datetime) between Getdate() and Getdate() -1

No comments:

Post a Comment