how to select using where clause? - sql

I have two dates, From date and To Date.
Also i have two time fields, From Time and To Time.
The date field in the database is Datetime. I need to select data according to both date and time.
This is my query for selecting data between 13:00 to 15:00, but it is not suitable for 20:00 to 08:00.
where Date>= '2/01/2012' AND Date<'2/28/2013'
AND CAST(Date AS TIME) BETWEEN '20:00' AND '08:00'

Without seeing your specific error/unexpected results, I think the problem is that 20 is greater than 8.
You'll have to use two conditions:
where Date>= '2/01/2012' AND Date<'2/28/2013' AND (CAST(Date AS TIME) > '20:00' OR CAST(Date AS TIME) < '08:00')
EDIT: fixed condition

Is this what you are after?
WHERE Date BETWEEN '2012-01-01 20:00:00.000' AND '2012-12-01 08:00:00.000'
It is a little bit unclear whether you are attempting to generate the WHERE clause variables dynamically?

You need to combine your "date" and "time" parts together.
This code will illustrate how to do this:
SELECT the_date
, the_time
, DateAdd(hh, DatePart(hh, the_time), the_date) As hour_added
, DateAdd(mi, DatePart(mi, the_time), the_date) As minute_added
, DateAdd(mi, DatePart(mi, the_time), DateAdd(hh, DatePart(hh, the_time), the_date)) As both_added
FROM (
SELECT Cast('2013-02-28' As datetime) As the_date
, Cast('08:30' As datetime) As the_time
) As example
You can then use the resultant values in your comparison

Related

get the first n characters of getdate()

I have a case compare date, hour of datetime column and current date,hour
select * from tbl where LEFT(EVENT_TIME_column,13) !=LEFT(GETDATE(),13)
EVENT_TIME_column format is '2019-08-15 12:32:40.0000000'
when i perform LEFT(GETDATE(),13) result is 'Aug 15 2019'
can you suggest how to get GETDate() in '2019-08-15 12' (date and hour)
If you want the format yyyy-MM-dd hh then can do this:
SELECT CONVERT(varchar(13),GETDATE(),120);
db<>fiddle
You can find a full list of all the style codes for CONVERT in the documentation: Date and Time Styles
However, it looks like you want to check if the date is within the current hour. That would be:
WHERE EVENT_TIME_column >= DATEADD(HOUR, DATEDIFF(HOUR, 0,GETDATE()),0)
AND EVENT_TIME_column < DATEADD(HOUR, DATEDIFF(HOUR, 0,GETDATE())+1, 0)
This explicitly avoids any functions on the column EVENT_TIME_column; which would make the query non-SARGable.
Don't use string functions on date/time values! There are perfectly good built-in functions:
where convert(date, event_time_column) = convert(date, getdate()) and
datepart(hour, event_time_column) = datepart(hour, getdate())
If you don't care about index usage, then use datediff():
where datediff(hour, event_time_column, getdate()) = 0
You can check this with 2 separate comparison as below. This is for checking Date and Hour part is same as date and hour part if GETDATE() or not.
WHERE CAST(EVENT_TIME_column AS DATE) = CAST(GETDATE() AS DATE)
AND DATEPART(HH,EVENT_TIME_column) = DATEPART(HH,GETDATE())
To check NOT EQUAL TO, Just replace = sign with != sign.
In addition, If I guess correct you are only trying to avoid records from running hour of to date. If this is the case, you can also filter your data with below logic-
WHERE EVENT_TIME_column < DATEADD(hh, DATEDIFF(hh, 0, getdate()), 0)

how to select only Date and Hour

Hi i have a column having record (2017-11-21 02:16:22.870).
I want select only Date and Hour (i.e:- 2017-11-21 02) from above records.
If you want to round down by hour, you can do:
select dateadd(hour, datediff(hour, 0, datetimecol), 0)
If you can live with two columns, I would recommend:
select cast(datetimecol as date) as datepart, datepart(hour, datetimecol) as hourpart
If you want the output in a particular format, you need to convert to a string:
select convert(varchar(13), datetimecol, 121)
use datepart for hour and convert for date
select concat( concat(convert(date,'2017-11-21 02:16:22.870'),':'), datepart(hour,'2017-11-21 02:16:22.870'))
2017-11-21:2
To select date from getdate() format
SELECT CONVERT(date, '2017-11-21 02:16:22.870')--2017-11-21
and select hour from getdate() format
datepart(HOUR, '2017-11-21 02:16:22.870')--2
I would use CONVERT() :
SELECT CONVERT(VARCHAR(13), col, 120)

Exclude time range in sql

In fact I have a table to store the details of calls and I need to filter the calls which entered the IVR after 16:00:00 till 06:59:00 the next day for ENTIRE MONTH I have used BETWEEN clause but it includes the details of all times of the month.
SELECT
[conversationId],
[conversationStart]
FROM
[Customer].[dbo].[vw_Conversations]
WHERE
conversationStart BETWEEN '2018-01-01 16:00:00.000' AND '2018-01-31 06:59:59.000'
Any help would be appreciated
Use DATEPART() function to test hour of the day. In your case, checking hours is enough:
SELECT conversationId,
conversationStart
FROM [Customer].[dbo].[vw_Conversations]
WHERE conversationStart BETWEEN '2018-01-01' AND '2018-02-01'
AND DATEPART(hour, conversationStart) NOT BETWEEN 7 AND 15
You need to just test the time component. I am not sure what date range you want, but the query is something like this:
SELECT conversationId, conversationStart
FROM Customer.dbo.[w_Conversations c
WHERE CONVERT(date, conversationStart) >= '2018-01-01' AND
CONVERT(date, conversationStart) < '2018-02-01' AND
(CONVERT(time, conversationStart) >= '16:00:00') OR
CONVERT(time, conversationStart) < '07:00:00')
);

Sql express time Query

am working with MS SQL express and Ignition SCADA by http://www.inductiveautomation.com/
In the SCADA package you are able to create tags from SQL query's. I am trying to use SQL tags to calculate the average packages per minute in a 30min time frame. I was able to do this with two tags and an expression
SELECT MAX(L8Total)
FROM Slicing_tot
WHERE t_stamp BETWEEN DATEADD(minute, -30, GETDATE()) AND GETDATE()
 
SELECT MIN(L8Total)
FROM Slicing_tot
WHERE t_stamp BETWEEN DATEADD(minute, -30, GETDATE()) AND GETDATE()
What I would like to do from here is store the expressions value and find the max and average for the last 30 days based on time. But I have no idea how to filter 30days of information at a certain time
IE what was the max packages per minute we had at 10:30 from the last 30 days
IE what was the average packages per minute we had at 11:45 form the last 30 days
Please keep in mind that I am new to SQL
SELECT DATEPART(MINUTE, t_stamp)
,MAX(L8Total)
,MIN(L8Total)
FROM Slicing_tot
WHERE ( CONVERT(DATE, t_stamp) >= CONVERT(DATE, GETDATE() - 30)
AND CONVERT(DATE, t_stamp) <= CONVERT(DATE, GETDATE())
)
AND ( CONVERT(TIME, #variable) >= '22:30'
AND CONVERT(TIME, #variable) <= '23:00'
)
GROUP BY DATEPART(MINUTE, t_stamp)
GETDATE()-30 will get you datetime of today minus 30 days ago. Since you are working with datetime field it is best to convert it to date to make sure that you get correct date range. Use of >= and <= is better than between because you is always clear what you doing. Read #Aaron's blog
than for the second part just convert your datetime column to time to limit to specific range during the day.
The following would select between 10 & 11 AM over those 30 days
SELECT MIN(L8Total)
FROM Slicing_tot
WHERE t_stamp BETWEEN DATEADD(dd, -30, GETDATE()) AND GETDATE()
and Datepart(hh,t_stamp) between 10 and 11
or you could compare the time part of the t_stamp to time
SELECT MIN(L8Total)
FROM Slicing_tot
WHERE t_stamp BETWEEN DATEADD(dd, -30, GETDATE()) AND GETDATE()
and convert(time, t_stamp) between '10:30:00.000' and '10:31:00.000'
which would give you the results between 10:30 and 10:31 inclusive of the end points over the last 30 days.

Comparing results with today's date?

Is there a way to use the Now() function in SQL to select values with today's date?
I was under the impression Now() would contain the time as well as date, but today's date would have the time set to 00:00:00 and therefore this would never match?
OK, lets do this properly. Select dates matching today, using indexes if available, with all the different date/time types present.
The principle here is the same in each case. We grab rows where the date column is on or after the most recent midnight (today's date with time 00:00:00), and before the next midnight (tomorrow's date with time 00:00:00, but excluding anything with that exact value).
For pure date types, we can do a simple comparison with today's date.
To keep things nice and fast, we're explicitly avoiding doing any manipulation on the dates stored in the DB (the LHS of the where clause in all the examples below). This would potentially trigger a full table scan as the date would have to be computed for every comparison. (This behaviour appears to vary by DBMS, YMMV).
MS SQL Server: (SQL Fiddle | db<>fiddle)
First, using DATE
select * from dates
where dte = CAST(CURRENT_TIMESTAMP AS DATE)
;
Now with DATETIME:
select * from datetimes
where dtm >= CAST(CURRENT_TIMESTAMP AS DATE)
and dtm < DATEADD(DD, 1, CAST(CURRENT_TIMESTAMP AS DATE))
;
Lastly with DATETIME2:
select * from datetimes2
where dtm2 >= CAST(CURRENT_TIMESTAMP AS DATE)
and dtm2 < DATEADD(DD, 1, CAST(CURRENT_TIMESTAMP AS DATE))
;
MySQL: (SQL Fiddle | db<>fiddle)
Using DATE:
select * from dates
where dte = cast(now() as date)
;
Using DATETIME:
select * from datetimes
where dtm >= cast((now()) as date)
and dtm < cast((now() + interval 1 day) as date)
;
PostgreSQL: (SQL Fiddle | db<>fiddle)
Using DATE:
select * from dates
where dte = current_date
;
Using TIMESTAMP WITHOUT TIME ZONE:
select * from timestamps
where ts >= 'today'
and ts < 'tomorrow'
;
Oracle: (SQL Fiddle)
Using DATE:
select to_char(dte, 'YYYY-MM-DD HH24:MI:SS') dte
from dates
where dte >= trunc(current_date)
and dte < trunc(current_date) + 1
;
Using TIMESTAMP:
select to_char(ts, 'YYYY-MM-DD HH24:MI:SS') ts
from timestamps
where ts >= trunc(current_date)
and ts < trunc(current_date) + 1
;
SQLite: (SQL Fiddle)
Using date strings:
select * from dates
where dte = (select date('now'))
;
Using date and time strings:
select dtm from datetimes
where dtm >= datetime(date('now'))
and dtm < datetime(date('now', '+1 day'))
;
Using unix timestamps:
select datetime(dtm, 'unixepoch', 'localtime') from datetimes
where dtm >= strftime('%s', date('now'))
and dtm < strftime('%s', date('now', '+1 day'))
;
Backup of SQL Fiddle code
There is no native Now() function in SQL Server so you should use:
select GETDATE() --2012-05-01 10:14:13.403
you can get day, month and year separately by doing:
select DAY(getdate()) --1
select month(getdate()) --5
select year(getdate()) --2012
if you are on sql server 2008, there is the DATE date time which has only the date part, not the time:
select cast (GETDATE() as DATE) --2012-05-01
Not sure what your asking!
However
SELECT GETDATE()
Will get you the current date and time
SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))
Will get you just the date with time set to 00:00:00
Just zero off the time element of the date. e.g.
SELECT DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0)
I've used GetDate as that's an MSSQL function, as you've tagged, but Now() is probably MySQL or you're using the ODBC function call, still should work if you just replace one with the other.
Not sure exactly what you're trying to do, but it sounds like GETDATE() is what you're after. GETDATE() returns a datetime, but if you're not interested in the time component then you can cast to a date.
SELECT GETDATE()
SELECT CAST(GETDATE() AS DATE)
Building on the previous answers, please note an important point, you also need to manipulate your table column to ensure it does not contain the time fragment of the datetime datatype.
Below is a small sample script demonstrating the above:
select getdate()
--2012-05-01 12:06:51.413
select cast(getdate() as date)
--2012-05-01
--we're using sysobjects for the example
create table test (id int)
select * from sysobjects where cast(crdate as date) = cast(getdate() as date)
--resultset contains only objects created today
drop table test
I hope this helps.
EDIT:
Following #dwurf comment (thanks) about the effect the above example may have on performance, I would like to suggest the following instead.
We create a date range between today at midnight (start of day) and the last millisecond of the day (SQL server count up to .997, that's why I'm reducing 3 milliseconds). In this manner we avoid manipulating the left side and avoid the performance impact.
select getdate()
--2012-05-01 12:06:51.413
select dateadd(millisecond, -3, cast(cast(getdate()+1 as date) as datetime))
--2012-05-01 23:59:59.997
select cast(getdate() as date)
--2012-05-01
create table test (id int)
select * from sysobjects where crdate between cast(getdate() as date) and dateadd(millisecond, -3, cast(cast(getdate()+1 as date) as datetime))
--resultset contains only objects created today
drop table test
If you have a table with just a stored date (no time) and want to get those by "now", then you can do this:
SELECT * FROM tbl WHERE DATEDIFF(d, yourdate, GETDATE())=0
This results in rows which day difference is 0 (so today).
For me the query that is working, if I want to compare with DrawDate for example is:
CAST(DrawDate AS DATE) = CAST (GETDATE() as DATE)
This is comparing results with today's date.
or the whole query:
SELECT TOP (1000) *
FROM test
where DrawName != 'NULL' and CAST(DrawDate AS DATE) = CAST (GETDATE() as DATE)
order by id desc
You can try this sql code;
SELECT [column_1], [column_1], ...
FROM (your_table)
where date_format(record_date, '%e%c%Y') = date_format(now(), '%e%c%Y')
You can try:
WHERE created_date BETWEEN CURRENT_TIMESTAMP-180 AND CURRENT_TIMESTAMP
This worked for me:
SELECT * FROM table where date(column_date) = curdate()