SQL Server - Generate date field data in where clause - sql-server

My query is
Select * from Orders
where ordersdate Between '2013-10-10 00:00:00.00' and '2013-10-10 23:59:59.997'
I need to run this query on daily basis and it should be previous day dates. so how to generate dates in above format is what im struggling with.

Select *
from Orders
where ordersdate >= cast(dateadd(d, -1, getdate()) as date)
and ordersdate < cast(getdate() as date)
Instead of the additonal time you can use >= yesterday's date and < today.

DECLARE #StartDate DATETIME, #EndDate DATETIME
/* set the end date to midnight of the previous day */
SET #EndDate = CONVERT(DATETIME, CONVERT(VARCHAR(10), GETDATE(), 121), 121)
/* set the start date to 1 day previously (thereby getting midnight to midnight) */
SET #StartDate = DATEADD(day, -1, #EndDate)
/* you could use between, but orders placed at midnight might be counted twice (on subsequent day reports) */
Select * from Orders where ordersdate Between #StartDate AND #EndDate
/* or you could use >= and < to guarantee that a order placed at midnight will only be counted once */
Select * from Orders where ordersdate >= #StartDate AND ordersdate < #EndDate

select *
from orders
where datediff(d, ordersdate, getdate()) = 1
/edit/
As per Jason Musgrove comment - such query is easy to write and understand, but depend on rows count may become quite inefficent.

taking a slightly different approach (but probably not as good as Arvo's Answer) and there are quicker ways to perform the cast
select *
from orders
where cast(ordersdate as varchar(11)) = cast( dateadd(dd,-1,getdate()) as varchar(11) )

Related

How to get data between start and endate and also data must be greater than 2018 in SQL Server

I want to fetch data between start and end dates and also only the data which is greater than year 2018.
Example:
if Startdate = 2016-01-01,
Enddate = 2018-03-01
I need to fetch data only from 2018-01-01 to 2018-03-01.
How to do this in SQL Server?
I'll assume you're using #Startdate and #Enddate as parameters.
The easiest way is just include the additional criterion in the WHERE clause.
SELECT *
FROM mytable mt
WHERE mt.startdate >= #Startdate
and mt.enddate <= #Enddate
and mt.startdate >= '20180101';
This is one of those queries though, that when you see it again in 6 months, you'll ask who the heck wrote that crap (before you realise it was you).
While the above is accurate, a more pleasing version (where the logic is much easier to see) is to modify the #Startdate first
IF #Startdate < '20180101' SET #Startdate = '20180101';
SELECT *
FROM mytable mt
WHERE mt.startdate >= #Startdate
and mt.enddate <= #Enddate;
So, if #startDate and #endDate are parameters. You have to add a AND in order to check if startDate is greater than your base date (2018)
you can also replace the '2018-01-01' with an #baseDate parameter
SELECT
*
FROM
yourTable
WHERE
yourTable.startDate > #startDate
AND yourTable.startDate > '2018-01-01'
AND yourTable.endDate < #endDate

How to get last six month of data from DB using SQL Server?

I have tried many different queries that already given here, but it also shows previous year data, for example, if use this query
Dateadd(Month, Datediff(Month, 0, DATEADD(m, -6, current_timestamp)), 0)
or
DATEADD(m, -6, current_timestamp)
These will result in the last six months. In my case, I want to print the last six month data. But the problem is if there is a data with the same date and different in the year will also result with these query eg (the above query returns the result of '2018-03-27 10:04:52.537' and if there is a data with '2017-03-27 10:04:52.537' will also come with the result). Can anyone help me?
here is my query
DECLARE #date6MonthAgo DATETIME = DATEADD(m, -6, current_timestamp)
DECLARE #totalCount INT = (SELECT COUNT(*)
FROM [PSA].[ProductionOrder]
WHERE CreatedDate >= #date6MonthAgo)
DECLARE #openCount INT = (SELECT COUNT(*)
FROM [PSA].[ProductionOrder]
WHERE DocumentStatusCode=7
AND CreatedDate >= #date6MonthAgo )
SELECT #date6MonthAgo, #totalCount, #openCount
Try something like this, after putting in the correct IDcolumn, just to verify for yourself the dates that are being returned
DECLARE #date6MonthAgo DATETIME = DATEADD(m, -6, current_timestamp);
SELECT #date6MonthAgo;
SELECT CreatedDate, keycolumnID
FROM [PSA].[ProductionOrder]
WHERE DocumentStatusCode=7
AND CreatedDate >= #date6MonthAgo
ORDER BY CreatedDate;
You can use this for find the last 6 month data from current date,
DECLARE #fromdate as datetime, #todate as datetime
set #fromdate = (select DATEADD(month, -6, getdate()))
set #todate = getdate()
SELECT CreatedDate, keycolumnID
FROM [PSA].[ProductionOrder]
WHERE DocumentStatusCode=7
AND cast(CreatedDate as date) between cast(#fromdate as date) and cast(#todate as date)
ORDER BY CreatedDate;
If you want find last 6 month date from a specific date, so you can set that date in #fromdate and #todate parameters like this,
set #fromdate = (select DATEADD(month, -6, #Yourdate))
set #todate = #Yourdate

TSQL Search Query between two dates

I am having a little trouble figuring out how to write a query that seems pretty straight forward.
The problem is in my WHERE clause. There are two fields in my table. A timestamp for when the task has started startTime and a timestamp for when the task was completed endTime/ Both of these fields are Datetime.
In my UI, I allow the person to select a Start Date and End Date and their filtering option.
The date logic should be as follows:
Everything where the StartTime is >= #startDate but < #endDate and the EndTime is <=#endDate but > #startDate.
I have done date ranges before using a single date in the database but not multiple so I am confused.
Any thoughts?
-- Fetch our data
SELECT [recordID],
[ItemID],
[QID],
[NTID],
[EmpID],
[FirstName],
[LastName],
[SupQID],
[SupEmpID],
[SupFirstName],
[SupLastName],
[Location],
[Department],
[Skillset],
[BudgetMarket],
CONVERT (VARCHAR (20), [startTime], 100) AS startTime,
CONVERT (VARCHAR (20), [endTime], 100) AS endTime,
COALESCE (DATEDIFF(SECOND, startTime, endTime), 0) AS totalTimeSeconds
FROM itemTracker_records
WHERE (#employee IS NULL OR (QID = #employee))
AND (#supervisor IS NULL OR (supQID = #supervisor))
AND CAST(endTime as Date) >= #startDate AND CAST(endTime as Date) < #endDate
FOR XML PATH ('results'), TYPE, ELEMENTS, ROOT ('root');
Shouldn't it be as simple as :
WHERE (StartTime >= #startDate AND #startDate < #endDate )
AND (EndTime <= #endDate AND #endDate > #startDate)
Or, slightly shorter:
WHERE StartTime between #startDate AND #endDate
AND EndTime between #startDate AND #endDate
Assuming "good" data, i.e. tasks always end after they start and the user supplied range is valid:
where startTime >= #StartDate and endTime <= #EndDate
As long as that is true then the task time span must be contained within the user specified range.
Note that a common problem is attempting to find date/time values between a pair of dates. To include all times on the last day it is necessary to add one day to #EndDate and remove equality from the comparison.

Show 0 if null in query

I am running a sql query that is omitting the day if the return count is 0. I want my query to return the day and a 0 count if the the count is 0. Snare I have is that if 0 were sold for the day, the day is omitted from my return results.
SELECT ISNULL([day],0) As [day], COUNT(ISNULL(Sold,0)) As [Sold]
FROM productionInfo
You're drawing information from a single table, productionInfo. If productionInfo has no rows with that date information (because there are no widgets sold on that date), how does it know what dates to use?
You might want to look at using a Numbers Table to get a row for each day of the month/year, then join that to productionInfo so you have a day value available, even if there was no production that day.
This will give you a dates table:
CREATE FUNCTION dbo.DatesTable (#startDate DATETIME, #endDate DATETIME)
RETURNS #retTable TABLE (DateValue DATETIME)
AS
BEGIN
DECLARE #currentDate DATETIME
SET #currentDate = #startDate
WHILE (DATEDIFF(dd, #currentDate, #endDate) >= 0)
BEGIN
INSERT INTO #retTable VALUES (#currentDate)
SET #currentDate = DATEADD(dd, 1, #currentDate)
END
RETURN
END
Then your query will look like:
SELECT dt.DateValue AS [day], COUNT(Sold) AS [Sold]
FROM dbo.DatesTable('2-1-2014', '2-10-2014') dt
LEFT JOIN productionInfo pi ON pi.day = dt.DateValue
GROUP BY dt.DateValue

TSQL Filtering a query by time / hours

Ok, I'm running query builder out of visual studio 2008. I'm trying to filter the results of the query by time; that is, I want to pull everything from the start of yesterday to noon yesterday.
I've been using GETDATE()-1 for yesterday, which pulls up a timestamp mm/dd/yyyy hh:mm:ss
however, it pulls the current time. to get it to run from the start of the day I appended the timestamp to remove the time itself, so it started at the beginning of the day:
convert(varchar(10), getdate()-1, 120)
so I'm using between to find the range, I have:
BETWEEN convert(varchar(10), getdate()-1, 120) AND // this is where I need it to cut off at noon.
I'm understanding that datetime is a data type here, so I tried subtracting the hours/minutes/seconds using date part, but datepart() only returns ints and doesn't affect the time.
thoughts? how do I get this to cut off at noon
Try this:
--Variables
declare #now datetime = getdate(),
#yesterday datetime
--Yesterday starting datetime
select #yesterday = convert(datetime, convert(date, dateadd(day,-1,#now)))
--Your query to filter between y'day start and y'day noon
--Note that between means inclusive boundary values. (or use >= and <=)
select * from yourTable
where dateCol between #yesteray and dateadd(hour,12,#yesterday)
DECLARE
#Min DATETIME
, #Max DATETIME
SELECT
#Min = DATEADD(DAY, -1, CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME))
, #Max = DATEADD(HOUR, 12, CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME))
SELECT *
FROM <Table> x
WHERE x.[Date] BETWEEN #Min AND #Max
SELECT * FROM T WHERE YourDate BETWEEN CAST(GETDATE()-1 As DATE) AND DATEADD(Hour, -12, CAST(CAST(GETDATE() As DATE) As DATETIME) )
Beware because BETWEEN will include lower and upper boundaries, so you can simply replace BETWEEN with x >= y and y < z if you don't want yesterday at 12:00 to be taken in account
between DateAdd(day, -1, cast(getdate() as date)) and DateAdd(hour, -12, cast(getdate() as date))
Edit: As mentioned in the comments, you can't use hours with a date, you have to cast it back to a datetime, thus:
between DateAdd(day, -1, cast(getdate() as date)) and DateAdd(hour, -12, cast(cast(getdate() as date) as datetime))
If you want to get the results from last 30 mins you need to use this. You can change MINUTE to HOUR too.
--Get now, hour and second included
DECLARE #NOW DATETIME = GETDATE()
--Get 30 mins from now
DECLARE #TranDate DATETIME
SET #TranDate = CONVERT(DATETIME, CONVERT(DATETIME, DATEADD(MINUTE,-30,#NOW)))
After That, add below code to your where statement,
AND TK.TransactionDate >= #TranDate

Resources