Convert Date/Time to Date - sql-server

I have a query which runs and I would like to return records where the date is greater than or equal to a particular date. The column I'm querying against is datetime format.
SELECT COUNT(RSO_ParentID), AssignedDateTime
FROM Task
WHERE OwnerTeam='2nd Line Support' AND AssignedDateTime>='2015-09-01 00:00:00.000'
GROUP BY AssignedDateTime
Is there a way of having filtering on the date part of AssignedDateTime, and searching relative to the current date (i.e. search for the previous 7 days)?
Thanks,
Matt

You could do it like this in MSSQL
SELECT COUNT(RSO_ParentID), AssignedDateTime
FROM Task
WHERE OwnerTeam='2nd Line Support' AND AssignedDateTime>=DATEADD(D,-7, GETDATE())
GROUP BY AssignedDateTime

Note: This question was not tagged SQL Server 2005 when I answered it. I am leaving the answer, because it is appropriate for SQL Server 2008+.
If you just care about the date and not the time, you need a combination of casting and datediff():
SELECT COUNT(RSO_ParentID), AssignedDateTime
FROM Task
WHERE OwnerTeam = '2nd Line Support' AND
AssignedDateTime >= dateadiff(day, -7, cast(getdate() as date))
GROUP BY AssignedDateTime;
Note that you can also express this using functions on AssignedDateTime. That is generally a bad idea because it often prevents the use of indexes for the query.
I also am guessing that you want the results by day:
SELECT COUNT(RSO_ParentID), cast(AssignedDateTime as date)
FROM Task
WHERE OwnerTeam = '2nd Line Support' AND
AssignedDateTime >= dateadiff(day, -7, cast(getdate() as date))
GROUP BY cast(AssignedDateTime as date);
or a total, in which you don't want a group by clause:
SELECT COUNT(RSO_ParentID)
FROM Task
WHERE OwnerTeam = '2nd Line Support' AND
AssignedDateTime >= dateadiff(day, -7, cast(getdate() as date));

If you are using MSSQL, use DATEDIFF.
SELECT COUNT(RSO_ParentID), AssignedDateTime
FROM Task
WHERE OwnerTeam='2nd Line Support' AND DATEDIFF(DAY,AssignedDateTime,GETDATE()) <=7
GROUP BY AssignedDateTime

Try this, it will check only date part, but not time part
SELECT COUNT(RSO_ParentID), AssignedDateTime
FROM Task
WHERE OwnerTeam='2nd Line Support' AND CAST(AssignedDateTime AS DATE) >=
DATEADD(D,-7, GETDATE())
GROUP BY AssignedDateTime

Related

In SSMS how can I use the DATEADD function to grab all values between '2018-09-01 00:00:00.000' and '2018-09-01 023:59:00.000'

I am using SQL Server Management Studio 2014 and trying to write a query to grab all values that have the next days date for orders I do not want to hard code the between clause for the date and want to use DateAdd or a similar function so it works consistently without changing the syntax. Example of hard coded query is below.
SELECT OrderId
FROM [XXXX].[dbo].[INBOUNDORDHEADER]
between '2018-09-01 00:00:00.000' and '2018-09-01 023:59:00.000'
What is the best way to write the syntax for this utilizing the DATEADD or similar function?
Is there a way I can not discriminate against the time of the values retrieved? For example just pull everything with 2018-09-01 and not exclude records based on their time format
Can I use AddDate with between to accomplish this?
Making the WHERE clause SARGABLE so that it can benefit from indexes can greatly improve performance. It is best not to fiddle about with trying to get the "last" time in a day, just use a half-open interval:
declare #Today as DateTime = Cast( GetDate() ); -- Strip the time-of-day.
select OrderId
from [XXXX].[dbo].[INBOUNDORDHEADER]
where DateAdd( day, 1, #Today ) <= OrderDate and OrderDate < DateAdd( day, 2, #Today );
Not super elegant, but you can use a cast to DATE to strip the time:
SELECT OrderId
FROM [XXXX].[dbo].[INBOUNDORDHEADER]
BETWEEN DATEADD(day, 1, CAST(GETDATE() As DATE)) AND DATEADD(day, 2, CAST(GETDATE() As DATE))
This will give you the date range between midnight tomorrow and midnight the day after. Using your example and today's date, it'll be BETWEEN '2018-09-01 00:00:00' AND '2018-09-02 00:00:00'
I think the 'cleanest' way is to use DATEFROMPARTS and DATEPART methods:
SELECT OrderId
FROM [XXXX].[dbo].[INBOUNDORDHEADER]
WHERE DATEFROMPARTS(
DATEPART(YEAR, OrderDate),
DATEPART(MONTH, OrderDate),
DATEPART(DAY, OrderDate)) = '2018-09-01'
Edit: This is not good for performance. See HABO's answer for the optimal way to do this.

How to get newly inserted records in SQL Server per day

I am using a SQL Server database, and I need to get the total number of newly inserted records per day, per week, per month, and per year separately. I have a column in my SQL Server database that records the date and time (the data type is datetime).
I used the following code to get the daily records but doesn't work
SQL:
select count(*)
from dbo.Firsttimer
where (Signed_in) = date(date_sub(now());
Please how do I achieve this?
You'll need to use conditional aggregation, i.e. a count(case...), along with the getdate() and dateadd() functions.
select
Today = cast(getdate() as date)
,TodayCount = count(case when cast(Signed_in as date) = cast(getdate() as date) then Signed_in)
,RollingWeekCount = count(case when cast(Signed_in as date) >= dateadd(day,-7,cast(getdate() as date)) then Signed_in)
,Rolling30Days = count(case when cast(Signed_in as date) >= dateadd(day,-30,cast(getdate() as date)) then Signed_in)
,Rolling365Days = count(case when cast(Signed_in as date) >= dateadd(day,-365,cast(getdate() as date)) then Signed_in)
from
YourTable
If you wanted this split out for each week, each month, each year... then that's best handled another way. However you didn't specify this so I provided a rolling method.
In SQL Server, you get the current DateTime value using the built in GetDate() method.
So to get all the records that have today's date in a specific DateTime column you can do something like this:
DECLARE #FromDate date = CAST(GETDATE() AS date)
DECLARE #ToDate date = DATEADD(DAY, 1, #FromDate)
SELECT COUNT(*)
FROM dbo.Firsttimer
WHERE [Signed_in] >= #FromDate
AND [Signed_in] < #ToDate
To get the first and last day of the week you can read this SO post,
first day and last day of the month on this SO post,
and first and last day of the year on this SO post

How to retrieve all rows with a date in this and the next week? SQL Server

I have a Tasks table that contains Date, Description and WorkerID columns. I want to write a stored procedure that selects all tasks from this week and the following week. Can someone help me get to a solution please? I am not so good at this.
If indexing (performance) isn't a concern then it's a simple expression if your week coincides with the SQL Server setup:
where datediff(week, getdate(), [Date]) between 0 and 1
The snippet below is another option that works with both dates and datetimes. It's possible to adapt it to work with any ##datefirst setting but I'm just going to assume that the setting matches with the start of week you're looking to report on.
where
[Date] >= dateadd(day, 1 - datepart(weekday, getdate()), cast(getdate() as date))
and [Date] < dateadd(day, 15 - datepart(weekday, getdate()), cast(getdate() as date))
The following should give you what you want (assuming Monday is the first day of the week, and that the DBMS is SQL Server):-
select *
from Tasks
where [Date]
between
dateadd(dd,-(datepart(dw,[Date])-2),[Date]) --Monday of this week
and
dateadd(dd,13,dateadd(dd,-(datepart(dw,[Date])-2),[Date])) --Sunday of next week

Select Records for which the date field is spent a year

I have a table with columns
TypeExame, DateExame
How can I select all records with (Now-DateExame) > = 365 days?
select *
from MyTable
where datediff (day, DateExame, getdate()) >= 365
See DATEDIFF and GETDATE for further details.
If you have an index on DateExame, putting the condition like this will enable its usage:
SELECT *
FROM atable
WHERE DateExame <= DATEADD(DAY, -365, CAST(GETDATE() AS date))
;
The above references the date data type, which means you'd need at least SQL Server 2008 to run that. To make it work in earlier versions, you could rewrite the condition like this:
WHERE DateExame <= DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()) - 365, 0)
Basically, the modified version uses the DATEADD/DATEDIFF method of truncating a datetime value with a minor tweak to also subtract 365 days along the way.
However, if all your DateExame values are dates without the time part, this simpler version should work just as well:
WHERE DateExame <= DATEADD(DAY, -365, GETDATE())
That is, removal of GETDATE()'s result's time part would be perfectly unnecessary.
Try this one :
select *
from MyTable
where datediff (day, DateExame, getdate()) >= 365
By Using Datediff function you can subtract two dates . you can pass first argument as minute , day , month , year etc .

Date part function in SQL server

I have a sample data set below:
Date
01/01/2010
01/02/2010
01/03/2010
Running the query below gives:
SELECT
DATEPART (MONTH, Date) AS MONTH
FROM MYTABLE
OUTPUT:
MONTH
1
I would like to the output as mm/dd/yyyy format as below.
MONTH
01/01/2010
Could someone please look into it?
Thanks a bunch!
If you want to truncate date to a month, you might use:
select dateadd(m, datediff(m, 0, getdate()), 0)
Put your date column instead of getdate().
If you are running the latest SQL Server 2012, you can use datefromparts function to make a "first of the month" date, like this:
SELECT
DATEFROMPARTS(YEAR(Date), MONTH(Date), 1) AS FIRST_OF_THE_MONTH
FROM MYTABLE

Resources