Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the best way to get the past 24 hour results in T-SQL?

I'm working on creating a chart for my client and they want to get the total customer count over a 24 hour, 3 day, 1 week, 1 month, etc period. I'm honestly not the best with SQL, so generating these queries aren't my forte.

In regards to getting the customers over 24 hours, I've come across two "where" statements that may work, but I'm not sure which is the best.

First version:

WHERE DATEDIFF(hh,CreatedDate,GETDATE())>24

Second Version:

WHERE CreatedDate >= DATEADD(HH, -24, GETDATE())

The first version generates 21 rows and the second generates 17 rows (from the same dataset, of course) so obviously one is more accurate than the other. I'm leaning towards the first, but I would like your opinion... please.

Thanks, Andrew

like image 842
AJ Tatum Avatar asked Jul 20 '10 19:07

AJ Tatum


People also ask

How do I get the last 24 hour data in SQL?

If you want to select the last 24 hours from a datetime field, substitute 'curate()' with 'now()'. This also includes the time.

How can get last 30 days data from a table in SQL Server?

SELECT * FROM product WHERE pdate >= DATEADD(day, -30, getdate()).

How do I get the last working day in SQL?

SELECT DATEADD(DAY, CASE (DATEPART(WEEKDAY, GETDATE()) + @@DATEFIRST) % 7 WHEN 1 THEN -2 WHEN 2 THEN -3 ELSE -1 END, DATEDIFF(DAY, 0, GETDATE())); This will work for all language and DATEFIRST settings.

How can add 24 hours to current date in SQL Server?

If you are using mySql or similar SQL engines then you can use the DATEADD method to add hour, date, month, year to a date. select dateadd(hour, 5, now()); If you are using postgreSQL you can use the interval option to add values to the date.


1 Answers

Avoid the first version. First, because it disables index utilization. The second (functional) issue with the first version is, DATEDIFF(HOUR...) returns all values less than 25 hours. Try this for clarity:

SELECT DATEDIFF(HOUR, '2010-07-19 00:00:00', '2010-07-20 00:59:59.99')
like image 121
Florian Reischl Avatar answered Nov 10 '22 16:11

Florian Reischl