Why am I getting '2009' data? What am i doing wrong with the WHERE Clause?
SELECT CONVERT(varchar, EventDate, 101) AS EVENTDATE,
CONVERT(varchar, ClosedDate, 101) AS CLOSEDDATED,
DATEDIFF(Day,EventDate,ClosedDate) AS DiffDate,
FROM mytable
WHERE (CONVERT(varchar, EventDate, 101) BETWEEN '04/01/2010' AND '04/30/2010')
You're doing a string comparison, which goes from left to right. '04/10/2009' is between '04/0' and '04/3'.
If the field you're comparing is a DATETIME, don't try to convert it. SQL server can convert the strings to dates and do the comparison properly.
If you use a supported date format, SQL Server will implicitly convert the string to a DATETIME:
SELECT CONVERT(varchar, EventDate, 101) AS EVENTDATE,
CONVERT(varchar, ClosedDate, 101) AS CLOSEDDATED,
DATEDIFF(Day,EventDate,ClosedDate) AS DiffDate,
FROM mytable
WHERE EventDate BETWEEN '2010-04-01' AND '2010-04-30'
Your query is just doing string comparison, which has no bearing on date spans.
Your WHERE clause may be doing string comparison instead of date comparison. If you want to do a date comparison you can change
CONVERT(varchar, EventDate, 101)
to
CAST (CONVERT(varchar, EventDate, 101) AS DATETIME)
You really don't need all the conversion. The dates from the calendar will have the right start and end times. You also want to consider events that might go past the end date or start before the date and end within the date range. Or finally start before and go past...
Here's some code we use
(EventStartDtTm >= startDt and EventStartDtTm <= endDt)
|| (EventStartDtTm <= startDt and EventEndDtTm >= startDt)
-- patrick
Related
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)
I am trying to use my query as the current day for my SQL query.
What I am trying below returns 0 records:
select *
from [TEST].[dbo].LIMIT
where endOfDay = GETDATE()
select *
from [TEST].[dbo].LIMIT
where endOfDay = dateadd(dd, datediff(dd, 0, getdate()), 0)
where endOfDay >= getdate() and endOfDay < getdate() + 1
An example date would be 2019-07-09 00:00:00.0
Also if there is no given date for today's date can I get a range of dates?
Any help would be appreciated, thanks.
First, you need to omit the quotes or else 'GETDATE()' is just a string.
Second, to match by "day", you need to strip the time part from the result of GETDATE(), which you can do by using CAST(GETDATE() as DATE) instead:
select *
from [TEST].[dbo].LIMIT
where endOfDay = CAST(GETDATE() as DATE)
For this to work best, the endOfDay column also needs to be of type DATE. If it is something else, you need to also CAST or CONVERT endOfDay to a DATE.
Using quotes makes it looking for a meaningless literal 'GETDATE()' to find nothing
You can use
with LIMIT(today, EndOfDay) as
(
select CONVERT(DATETIME, CONVERT(date, GETDATE())), GETDATE()
)
select EndOfDay
from LIMIT
where EndOfDay >= today and EndOfDay < today + 1;
Demo
Try this:
select *
from [TEST].[dbo].LIMIT
where cast(endOfDay as date) = cast(GETDATE() as date)
SQL Fiddle to see what the date will be compared with.
GETDATE() returns the server's current date and time. Unless you have any records that match that exactly, it doesn't make sense to use GETDATE. It doesn't look like you do based on the endOfDay column name.
The other criteria you show,
dateadd(dd,datediff(dd,0,getdate()),0) is essentially stripping the time off and returning midnight of the current date.
select getdate() 2019-07-11 15:10:09.287
select dateadd(dd,datediff(dd,0,getdate()),0) 2019-07-11 00:00:00.000
Assuming you don't care about time, convert both EndofDay and Getdate to a simple date for comparison.
select * from [TEST].[dbo].LIMIT where convert(date,EndOfDay) = convert(date,getdate())
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)
I am trying to get MIN and MAX time from a Datetime (InOut) column but output is same for both column.
My query:
SELECT
CONVERT(NVARCHAR(12),MIN(Punch_history.Ecode)) as EmpCode,
CONVERT(NVARCHAR(12),MIN(EmployeeMaster.RecommandedBy)) as EmpID,
convert(date, InOut) as Report_date,
CONVERT(VARCHAR(10),(InOut),108) as InTime,
CONVERT(VARCHAR(10),(InOut),108) as OutTime,
CONVERT(NVARCHAR(12),MIN(TID)) as LOCATION
FROM Punch_history inner join EmployeeMaster on Punch_history.ECode = EmployeeMaster.Ecode
where CAST (InOut as DATE) between CAST(getdate() -1 as DATE ) and CAST(getdate() -1 as DATE ) and
EmployeeMaster.RecommandedBy like 'M0%' group by EmpID,InOut
Try grouping by the converted date instead of inout.
SELECT
CONVERT(NVARCHAR(12),MIN(Punch_history.Ecode)) as EmpCode,
convert(date, InOut) as Report_date,
CONVERT(NVARCHAR(10),min(InOut),108) as InTime,
CONVERT(NVARCHAR(10),max(InOut),108) as OutTime
FROM Punch_history
where CAST (InOut as DATE) between CAST(getdate() -1 as DATE )
and CAST(getdate() -1 as DATE )
group by EmpID, convert(date, InOut)
In addition to the grouping issue your where clause is quite strange. First of all using shortcuts for date math is a no win situation. It will fail with datetime2. And using between two identical values is just strange.
SELECT
CONVERT(NVARCHAR(12), MIN(Punch_history.Ecode)) as EmpCode,
convert(date, MIN(InOut)) as Report_date,
CONVERT(NVARCHAR(10), min(InOut), 108) as InTime,
CONVERT(NVARCHAR(10), max(InOut), 108) as OutTime
FROM Punch_history
where convert(date, InOut) = convert(date, dateadd(day, -1, getdate()))
group by EmpID
The major issue is that you should not group by InOut (datetime), that is why in the result max and min are the same. Actually, this is cancelling the grouping which you want to happen on daily basis.
SELECT
CONVERT(NVARCHAR(12),MIN(Punch_history.Empcode)) as EmpCode,
CONVERT(DATE , Max(InOut)) as Report_date,
CONVERT(NVARCHAR(10),min(InOut),108) as InTime,
CONVERT(NVARCHAR(10),max(InOut),108) as OutTime
FROM Punch_history
where datediff(day, CAST(InOut as DATE ) , CAST(getdate() as DATE ) )=1
group by EmpID
In addition, if empid and empcode are 1-1 (logically they should be)
then you can group directly with empcode, or both of them
avoiding this rather strange Min(empcode).
Supposing we have the following records in an SQL Server table.
Date
19/5/2009 12:00:00 pm
19/5/2009 12:15:22 pm
20/5/2009 11:38:00 am
What is the SQL syntax for getting something like this one?
Date Count
19/5/2009 2
20/5/2009 1
You need to do any grouping on a Date only version of your datefield, such as this.
SELECT
CONVERT(VARCHAR(10), YourDateColumn, 101),
COUNT(*)
FROM
YourTable
GROUP BY
CONVERT(VARCHAR(10), YourDateColumn, 101)
I usually do this though, as it avoids conversion to varchar.
SELECT
DATEPART(yy, YourDateColumn),
DATEPART(mm, YourDateColumn),
DATEPART(dd, YourDateColumn),
COUNT(*)
FROM
YourTable
GROUP BY
DATEPART(yy, YourDateColumn),
DATEPART(mm, YourDateColumn),
DATEPART(dd, YourDateColumn)
EDIT: Another way to get just the date part of a datetime
DATEADD(d, 0, DATEDIFF(d, 0, YourDateColumn))
That would depend on your database engine. For SQL Server 2008 (and future versions), you can use the date type to do this.
select
convert(date, date_column_name) as Date,
count(1) as Count
from table_name
group by convert(date, date_column_name)
Depends on your DBMS. Example for Mysql:
SELECT DATE_FORMAT(dateColumn, '%e/%c/%Y') as `date`, COUNT(*)
FROM YourTable
GROUP BY `date`
What RDBMS are you on? Using Sybase, your query would look like this:
select date(datetimeColumn) as myDate, count(*) as myTotal
from thisTable
Group by myDate
Order by myTotal, myDate
After Googling found this one too...
SELECT CAST(FLOOR(CAST(Expr1 AS FLOAT)) AS DATEtime) AS Expr1,
COUNT(*) AS Expr2
FROM MY_TABLE
GROUP BY
CAST(FLOOR(CAST(Expr1 AS FLOAT)) AS DATEtime)
The cons?
High speed execution
The results returned are in the original locale. Ex for Greek 19/5/2009
Thank you all