select query using getdate() to after 15 days in sql server? - sql

name amount date
---------------------------------------
xxx 1000 2014-04-20 12:53:23.983
yyy 1500 2014-04-25 12:53:23.983
My output like this:
name amount date
--------------------------------------
xxx 1000 2014-04-20 12:53:23.983
My query:
alter proc K_VM_GetTaxdetails
as
begin
select name, amount, date
from K_VM_TaxDetails
where DATEADD(day, -15, GETDATE()) = date
end
I have tried like this but I am not getting required output.
If I have a date = 2014-04-20 12:53:23.983 in my table, I want to display all data before 15 days from that date.
How can I write in where condition?

This displays all rows in the last 15 days:
declare #now = select cast(floor(cast(getdate() as float)) as datetime); -- truncate time from datetime
select name, amount, date from K_VM_TaxDetails
where date >= dateadd(day, -15, #now);
This displays all rows for single day 15 days ago:
declare #now = select cast(floor(cast(getdate() as float)) as datetime); -- truncate time from datetime
select name,amount,date from K_VM_TaxDetails
where date >= dateadd(day, -15, #now) and
date < dateadd(day, -14, #now);

This will give you all data from the day 15 days ago
alter proc K_VM_GetTaxdetails
as
begin
declare #d datetime = dateadd(day, datediff(day, -15, getdate()), 0)
select name, amount, date
from K_VM_TaxDetails
where date >= #d -- retrieve from
and date < dateadd(day, 1, #d) -- retrieve to
end

Shows dates at least 15 days older than the current date:
select name,amount,date from K_VM_TaxDetails
where date <= DATEADD(day, -15, GETDATE())

I suggest to compare date with only date part and not time as including time in date comparison sometimes provided incorrect result.
Below query removes time part and compare only date.
select name, amount, date
from K_VM_TaxDetails
where (convert(date,[date]) >= DATEADD(day, -15, convert(date,GETDATE())) and convert(date,[date]) <= convert(date,GETDATE()))

alter proc K_VM_GetTaxdetails
as
begin
select name, amount, date
from K_VM_TaxDetails
where DATEADD(day, -15, SYSDATETIME()) = date
end

Related

Getdate() functionality returns partial day in select query

I have a query -
SELECT * FROM TABLE WHERE Date >= DATEADD (day, -7, -getdate()) AND Date <= getdate();
This would return all records for each day except day 7. If I ran this query on a Sunday at 17:00 it would only produce results going back to Monday 17:00. How could I include results from Monday 08:00.
Try it like this:
SELECT *
FROM SomeWhere
WHERE [Date] > DATEADD(HOUR,8,DATEADD(DAY, -7, CAST(CAST(GETDATE() AS DATE) AS DATETIME))) --7 days back, 8 o'clock
AND [Date] <= GETDATE(); --now
That's because you are comparing date+time, not only date.
If you want to include all days, you can trunc the time-portion from getdate(): you can accomplish that with a conversion to date:
SELECT * FROM TABLE
WHERE Date >= DATEADD (day, -7, -convert(date, getdate())
AND Date <= convert(date, getdate());
If you want to start from 8 in the morning, the best is to add again 8 hours to getdate.
declare #t datetime = dateadd(HH, 8, convert(datetime, convert(date, getdate())))
SELECT * FROM TABLE
WHERE Date >= DATEADD (day, -7, -#t) AND Date <= #t;
NOTE: with the conversion convert(date, getdate()) you get a datatype date and you cannot add hours directly to it; you must re-convert it to datetime.
Sounds like you want to remove the time. Correct? If so then do the following.
SELECT * FROM TABLE WHERE Date >= (DATEADD (day, -7, -getdate()) AND Date DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0))

Today Production - SQL Date Calculation case when

I have an issue regarding date calculations.
I have a datetime column called CreatedLocalTime date with this format: 2015-11-15 19:48:50.000
I need to retrieve a new column called Prod_Date with:
if “CreatedLocalTime” between
(CreatedLocalTime 7 AM)
& (CreatedLocalTime+1 7 AM)
return CreatedLocalTime date with DD/MM/YYYY format
On other words, today production = sum of yesterday from 7 AM till today at 7 AM.
Any help using case?
For day 7AM to day+1 7AM, you can try:
SELECT CAST(CreatedLocalTime as date)
...
FROM ...
WHERE ...
CreatedLocalTime >= DATEADD(hour, 7, CAST(CAST(CreatedLocalTime as date) as datetime))
AND
CreatedLocalTime < DATEADD(hour, 31, CAST(CAST(CreatedLocalTime as date) as datetime))
...
For previous day 7AM to day 7AM, replace 7 by -14 and 31 by 7.
Another way..
SELECT CASE WHEN CreatedLocalTime BETWEEN DATEADD(HOUR, 7,
CAST(CAST (CreatedLocalTime AS DATE) AS DATETIME))
AND DATEADD(HOUR, 31,
CAST(CAST (CreatedLocalTime AS DATE) AS DATETIME))
THEN REPLACE(CONVERT(NVARCHAR, CreatedLocalTime, 103), ' ', '/')
END AS CreatedLocalTime
You can write the else part for this, if needed
It looks like you want somthing along the lines of
DECLARE #StartDateTime Datetime
DECLARE #EndDateTime Datetime
SET #EndDateTime = DATEADD(hour, 7,convert(datetime,convert(date,getdate())) )
SET #StartDateTime = DATEADD(day, -1, #EndDateTime )
--Print out the variables for demonstration purposes
PRINT '#StartDateTime = '+CONVERT(nchar(19), #StartDateTime,120)
PRINT '#EndDateTime = '+CONVERT(nchar(19), #EndDateTime,120)
SELECT SUM (Production) AS Prod_Date FROM YourSchema.YourTable WHERE CreatedLocalTime >= #StartDateTime AND CreatedLocalTime < #EndDateTime
But you could also look at it as all the times which after you remove 7 hours from them are yesterday
SELECT SUM (Production) AS Prod_Date
FROM YourSchema.YourTable
WHERE DATEDIFF(day,DATEADD(hour, -7, CreatedLocalTime ))) = 1
The First version will be more efficient as the query will only have to do the date arithmetic once at the start while the second involved executing DATEDIFF and DATEADD for every record. This will be slower on large amounts of data.
The Gold plated solution would be to add a computed column to your table
ALTER TABLE YourSchema.YourTable ADD EffectiveDate AS CONVERT(date, DATEDIFF(day,DATEADD(hour, -7, CreatedLocalTime ))))
And then an index on that column
CREATE INDEX IX_YourTable_EffectiveDate ON YourSchema.YourTable (EffectiveDate )
So you can write
DECLARE #YesterDay date = DATEADD(day,-1, getdate())
SELECT SUM (Production) AS Prod_Date
FROM YourSchema.YourTable
WHERE EffectiveDate = #YesterDay

Getting records between 2 values in datediff function in SQL Server

Could you help me with this please.
I would like to get the records only if the DATEDIFF(day, due_date, GETDATE()) is more than 60 but is less than 90 days (or between 60 days and 90 days). If it is lesser than 60 or greater than 90 days, then leave it out).
Thank you!
a sargable alternative =>> it does not use functions on the data
-- DECLARE #today datetime = CAST(GETDATE() AS date) -- an option
DECLARE #today datetime = DATEADD(DAY, DATEDIFF(DAY,0, GETDATE()), 0)
SELECT
due_date
FROM some_table
WHERE (
due_date >= DATEDIFF(DAY, -90, #today)
AND due_date < DATEDIFF(DAY, -60, #today)
)
GETDATE() returns both date and the current time, so to get "today" at 00:00:00 you need to either cast getdate to a date, or use the dateadd function as shown above.
Then instead of calculating the days different for each row of data (2 functions for each row) and filtering on that calculated column (this could require hundreds, thousands or millions of calculations), why not compare the existing data to 2 calculated dates?
See: Sargable
Try this:
declare #today smalldatetime = getdate()
select
due_date
from
some_table
where
datediff(day, due_date, #today) > 60 and
datediff(day, due_date, #today) < 90

How to run a query for "Today's" date from 12:00am to 11:59PM

I have a simple query that pulls a payout report for our day. I'd like to automate this to send every night, however I want the report to run for That day 12:00AM - 11:59 PM daily... I will be sending the reports at 9:00 PM, so I suppose it will only need to get until 9:00 PM if that's easier.
Here is my query:
SELECT COUNT(*) AS Number, SUM(dblPayoutAmt) AS Amount
FROM Payouts
WHERE (dtCreated BETWEEN #startdate AND #enddate)
Don't use BETWEEN, use >= the start date and < a day past the end date:
WHERE (dtCreated >= #startdate AND dtCreated < DATEADD(day, 1, #enddate))
The reason is that BETWEEN will find up until 12:00am of the end date, but not past then.
UPDATED
For todays date, you can do this:
WHERE DATEADD(dd, 0, DATEDIFF(dd, 0, dtCreated)) = DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))
This will check that it has a dtCreated equal to some point today.
UPDATED
As #ScottChapman has pointed out, you can do the same thing without the conversion gymnastics by casting to the DATE type directly. This type is only available in MSSQL 2008 and later, however.
SET #StartDate = CAST(GETDATE() AS date)
SET #EndDate = DATEADD(MINUTE, -1, DATEADD(DAY, 1, #StartDate))
SELECT COUNT(*) AS Number, SUM(dblPayoutAmt) AS Amount
FROM Payouts
WHERE (dtCreated BETWEEN #startdate AND #enddate)
Some of these answers are close, but exclude times in the final minute of the day, like 11:59:30 PM. This query will include all of today:
SELECT COUNT(*) AS Number, SUM(dblPayoutAmt) AS Amount
FROM Payouts
WHERE (dtCreated >= CAST(GETDATE() as date) AND dtCreated < DATEADD(day, 1, CAST(GETDATE() as date)))
Note that this won't work in SQL Server 2005 or below, as the date type was added in SQL Server 2008.
As you're using SQL/Server 2008 you can remove any time element from a DATETIME column by converting it to DATE and select on that, E.g.
SELECT COUNT(*) AS Number, SUM(dblPayoutAmt) AS Amount
FROM Payouts
WHERE CONVERT(DATE,dtCreated) = CONVERT(DATE,GETDATE())
Very much more elegant
[EDIT]
Oh, I've just read Scott Chapman's answer, it's better because if dtCreated is indexed then the query will be more efficient.
Preceding answers also include data < 12.00 am
SELECT
COUNT(*) AS Number
, SUM(dblPayoutAmt) AS Amount
FROM
Payouts
WHERE
dtCreated >= dateadd( hour, 12, cast( cast( getdate() as date ) as datetime ))
and dtCreated < dateadd( second, -1, dateadd(day, datediff(day, -1, getdate()), 0))
set them both to SIMPLE date example: BETWEEN '2012-12-19' AND '2012-12-20' with no timestamp on them, then select the between.
In this example if you set the date for end to '2012-12-20 23:59:59.999' and then do a SELECT #enddate it returns '2012-12-21 00:00:00.000'
OR to use a function type syntax:
declare #mystart as datetime
declare #myend as datetime
set #mystart = dateadd(day,datediff(day,0,CURRENT_TIMESTAMP),0)
set #myend = dateadd(day,datediff(day,0,CURRENT_TIMESTAMP),1)
select #mystart, #myend
the #mystart here is set to ONLY the date part (time is 00:00:00.000) and the end is sent to that plus one day, so the BETWEEN syntax works.

TSQL SELECT previous date's records

I want to select all records from a table Log where the DateAndTime field values (of type datetime) are for the day before today, whatever day it is.
So if today is 2011-06-08, I want to select all rows where DateAndTime is greater than or equal to 2011-06-07 00:00:00 and also less than 2011-06-08 00:00:00.
I'm guessing the potential pitfall here would be it's behaviour on the 1st day of the month, as obviously a date like 2011-06-00 is invalid, and should be 2011-05-31.
For SQL Server 2008 you can use this.
select *
from [log]
where cast(DateAndTime as date) = cast(getdate()-1 as date)
Pre 2008 you can use this
select *
from [log]
where DateAndTime >= dateadd(d, datediff(d, 0, getdate())-1, 0) and
DateAndTime < dateadd(d, datediff(d, 0, getdate()), 0)
Related on DBA: Cast to date is sargable but is it a good idea?
SELECT * FROM Log
WHERE DateAndTime >= DATEADD(DAY,-1, CAST(GETDATE() AS DATE))
AND DateAndTime < CAST(CAST(GETDATE() AS DATE) AS DATETIME)
This example assumes SQL Server:
select *
from log
where convert(varchar(8), DateAndTime , 112) = convert(varchar(8), getdate()-1, 112)
Essentially, convert the date to yyyymmdd (the 112 parameter) and then check it is equal to yesterday's date (getdate()-1), also converted to yyyymmdd.
Assuming SQL Server
declare #today date
set #today = GETDATE()
select * from Log where DateAndTime between DATEADD(dd, -1, #today ) and #today
It should include conditional operator and not between .
Otherwise it includes today's records as well.
Declare #today date
Set #today = GETDATE()
Select YourcolumnNames from log
Where DateAndTime >= DATEADD(dd, -1, #today ) and DateAndTime < DATEADD(dd, -1, #today )
Moreover, you should mention the column name and * should be avoided in the select statement. This can improve the performance