Selecting all the data using time greater than 4pm - sql

I need to select the Data containing time > 4pm in datatimestamp every day in SQL Server Management Studio Microsoft SQL Server 2005 - 9.00.4060.00 (X64) DB table which has two years of data. What's the best way to do this? My time stamp has following format:DATETIME, '2005-10-13 16:00:00', 102. I have data at random times every afternoon. I need to get the data after 4pm for every day. Not just for one day.
For example i tried for one day like this:
SELECT Yield, Date, ProductType, Direct
FROM MIAC_CCYX
WHERE (Date < CONVERT(DATETIME, '2005-10-13 16:00:00', 102)) Thanks for help

It's hard to read your question, but assuming you really are using a datetime data type, you can use datepart to find any dates with a time greater than 4 PM:
WHERE datepart(hh, YourDate) > 16
Since you now need minutes as well, if you want records after 4:45 PM, you can cast your date to a time like this:
SQL Server 2000/2005
SELECT Yield, [Date], ProductType, Direct
FROM MIAC_CCYX
WHERE cast(convert(char(8), [Date], 108) as datetime) > cast('16:45' as datetime)
Essentially you cast the date using convert's Date and Time styles to convert the date to a time string, then convert back to a datetime for comparison against your desired time.
SQL Server 2008+
SELECT Yield, [Date], ProductType, Direct
FROM MIAC_CCYX
WHERE CAST([Date] as time) > CAST('16:45' as time)

This will work whatever your date is. This will not compare the dates. Rather, Datepart() will extract the hour element from datetime and comapre with your given time (e.g. 4 P.M. in your case)
SELECT * from <table> where DATEPART(hh, ModifiedDate) >= 16
I am assuming ModifiedDate as column name. this will return data from 4 P.M. to 11:59:59 P.M
Edit: I have checked this against MS SQL server 2012. Also it will work with datetime format.

Related

Is there a quick way to separate date and time from a time stamp in sql?

I am using sql to calculate the average daily temperature and max daily temperature based on a date timestamp in an existing database. Is there a quick way to accomplish this?
I am using dBeaver to do all my data calculations and the following code is what I have used so far:
SELECT
convert(varchar, OBS_TIME_LOCAL , 100) AS datepart,
convert(varchar, OBS_TIME_LOCAL, 108) AS timepart,
CAST (datepart AS date) date_local,
CAST (timepart AS time) time_local
FROM
APP_RSERVERLOAD.ONC_TMS_CUR_ONCOR_WEATHER;
The data format as follows:
ID time_stamp temp
--------------------------------------------
de2145 2018-07-16 16:55 103
There are multiple IDs with 24hrs of temperature data at 1 min increments.
I am not sure if I understand what you need but I will try:
Your question: "Is there a quick way to separate date and time from a time stamp in sql?"
Answer:
select to_char(datec, 'hh24:mi')
, to_char(datec, 'yyyy-mm-dd')
from test;
Use to_char with format to select date part and time part.
You seem to want aggregation:
SELECT convert(date, OBS_TIME_LOCAL) AS datepart,
avg(temp), max(temp)
FROM APP_RSERVERLOAD.ONC_TMS_CUR_ONCOR_WEATHER
GROUP BY convert(date, OBS_TIME_LOCAL);

Changing date to day before for certain daily time ranges in SQL

We have a table with a datetime field and need to get it to work properly with other tables that have date fields that work on system date, not calendar date.
Our system day runs until 1:59 AM, so anything after midnight until then is considered the day before in all of these tables (which don't actually show datetime, just date).
I am trying to figure out how I can create a date field where '2019-01-01 01:45:00.111' would read as '2018-12-31', but '2019-01-01 2:00:00.111' would read as '2019-01-01'.
Any ideas would be much appreciated.
Try this simple logic below by removing 120 minutes from your each datetime value and then cast the datetime value as date.
SELECT CAST(DATEADD(MINUTE,-120,<your_date_time_column>) AS DATE)
FROM <Your_Table>
You can make use of CASE WHEN.. clause to increment or decrement dates by 1 like below sample
SELECT CASE WHEN TO_CHAR(DATE,
'HH:MM') BETWEEN '00:00' AND
'01:45' THEN DATE-1 ELSE
DATE END FROM TABLE

SQL Server 2012 - Datetimeoffset field want to find noon time for each day

I have a database that sample well levels hourly each day for numerous wells. The datetime is in a datetimeoffset field called sampleTime.
I want to filter the data so that I will find 18:00:00 utc time for each day. I cannot seem to find a way to set the time correctly to look for this in an SQL statement. We have SQL Server 2012.
Here is what I have tried.
SELECT
wellID,
CAST(sampleTime AS time(0)) as "welltime",
CAST(sampleTime AS date) as welldate,
sampleTime, waterLevel
FROM
dbo.Real_Time_Water_Level_Data
WHERE
'welltime' = CAST('18:00:00' AS time)
ORDER BY
welldate
I get an message
Conversion failed when converting date and/or time from character string
I am assuming that is in my method of trying to set the '18:00:00' as a what I am looking for. I have tried it without the CAST and using a CONVERT but also getting errors.
What I really would love to get is the local noon time record for each day but I know that I would have to deal with CST and CDT and just decide to get the specific one of 18:00:00
Thanks.
SELECT
wellID,
CAST(sampleTime AS time(0)) as welltime,
CAST(sampleTime AS date) as welldate,
sampleTime, waterLevel
FROM dbo.Real_Time_Water_Level_Data
WHERE CAST(sampleTime AS time(0)) = CAST('18:00:00' AS time)
ORDER BY CAST(sampleTime AS date)
You can't use an alias in the where clause. You query has been modified to that effect.

Get tomorrows date

I am trying to get tomorrows date in a sql statement for a date comparison but it is not working.
Below is my code:
select *
from tblcalendarentries
where convert(varchar,tblcalendarentries.[Start Time],101)
= convert(varchar, GETDATE() +1, 101)
To get tomorrows date you can use the below code that will add 1 day to the current system date:
SELECT DATEADD(day, 1, GETDATE())
GETDATE()
Returns the current database system timestamp as a datetime value without the database time zone offset. This value is derived from the operating system of the computer on which the instance of SQL Server is running.
DATEADD(datepart , number , date)
Returns a specified date with the specified number interval (signed integer) added to a specified datepart of that date.
So adding this to your code in the WHERE clause:
WHERE CONVERT(VARCHAR, tblcalendarentries.[Start Time], 101) =
CONVERT(VARCHAR, DATEADD(DAY, 1, GETDATE()), 101);
First off, GETDATE() will get you today's date in the following format:
2013-04-16 10:10:02.047
Then using DATEADD(), allows you to add (or subtract if required) a date or time interval from a specified date. So the interval could be: year, month, day, hour, minute etc.
Working with Timezones?
If you are working with systems that cross timezones, you may also want to consider using GETUTCDATE():
GETUTCDATE()
Returns the current database system timestamp as a datetime value. The database time zone offset is not included. This value represents the current UTC time (Coordinated Universal Time). This value is derived from the operating system of the computer on which the instance of SQL Server is running.
Try the below:
SELECT GETDATE() + 1
This adds one day to current date
Specify size of varchar in convert()
where convert(varchar(11),tblcalendarentries.[Start Time],101) = convert(varchar(11), GETDATE() +1, 101)
I would write:
where
DATEADD(day,DATEDIFF(day,0,tblcalendarentries.[Start Time]),0) =
DATEADD(day,DATEDIFF(day,0,GETDATE()),1)
This avoids converting dates to strings entirely, whilst also removing the time portion from both values.

SQL Average Time from timestamp stored as string

I have two columns called date and starthour in a Microsoft SQL Server table.
Both columns are char; Another guy make it and I don't know why it was built in this way. :)
date starthour
20/01/2011 8:10:00
20/01/2011 8:20:00
20/01/2011 8:30:00
20/01/2011 8:40:00
21/01/2011 8:10:00
21/01/2011 8:20:00
21/01/2011 8:30:00
I want to determine the average starthour for each date.
date starthour
20/01/2011 8:25:00
21/01/2011 8:20:00
I tried the following:
SELECT date, Avg(cast(starhour as datetime())) AS starhour
FROM table
GROUP BY date
but it doesn't work.
SELECT [date],
CAST(DATEADD(second, AVG(DATEDIFF(second, 0 , starhour)), '00:00:00') AS time)
FROM dbo.test17
GROUP BY [date]
Demo on SQLFiddle
Let's not beat around the bush: you should fix this schema as soon as possible.
In the meantime, this will return the correct value.
select [date],
CONVERT(VARCHAR(8),
cast((avg(cast(cast(starhour as datetime) as float))) as datetime) , 108)
from table
group by [date]
Do not store dates, datetimes or timestamps as varchar. For instance, MySQL has native types for all three of these types, which guarantees that you won't have invalid data in them, and that MySQL will know how to treat them: http://dev.mysql.com/doc/refman/5.1/en/datetime.html
What you should do is have a single field, date, that is of timestamp type, containing both the date and the time. You should refactor your database and transfer over all your data to the new format by casting it, so that you never have to worry about again.
After that what you need to do differs based on your SQL flavour. For example, this answer will be for MySQL, but every flavour has different datetime functions (unfortunately!).
MySQL's datetime functions are http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html
Untested but something like:
GROUP BY EXTRACT(day from date)
AVG(EXTRACT(hour from date)*60 + EXTRACT(minute from date))