SQL Server comparing dates - sql

I have a table with Settlement details and I need a report in SSRS that returns settlement items with settlement date yesterday or older. I know this is trivial but there is something I am doing wrong and would appreciate help
This is for Microsoft SQL Server and basic table for simplification
Select
SETL.SettlementDay as SD,
SETL.Amount as Amount,
SETL.quantity as Q
From
Setlement as SETL
Where
SETL.SettlementDate < getdate()
This doesn't work for me. I expect the output would be settlements with settlement date older or equal to yesterday
Thanks

If you want yesterday or older, then use:
where SETL.SettlementDate < convert(date, getdate())
The conversion to date gets rid of the timestamp on getdate() (despite the name, it has the time as well as the date).
You might find this less confusing if you use current_timestamp (which is part of the SQL standard):
where SETL.SettlementDate < convert(date, current_timestamp)

could you try by using cast
Select
SETL.SettlementDay as SD,
SETL.Amount as Amount,
SETL.quantity as Q
From
Setlement as SETL
Where
cast( SETL.SettlementDate as date) < cast( getdate() as date)

Related

SQL Server : select count of Todays Transactions

I was wondering if someone could help me as I can't seem to find an answer to the following that I have been searching for.
Select
Count(pm1.number) As number
From
SCenter.probsummarym1 As pm1
Where
pm1.open_time >= Today()
I have the above that works great if I put in the date as '01-05-2015'
But I want today's date each day when it refreshes.
Sorry if this is pretty basic but I am just lost on this one
GETDATE() will return the current date and time.
You may then use a CAST() or CONVERT() to strip the time value and be left with just the date, ie.
SELECT CONVERT(VARCHAR(10), GETDATE(), 110)
The above code would return 05-19-2015 for today.
Select
Count(pm1.number) As number
From SCenter.probsummarym1 As pm1
Where
pm1.open_time >= GETDATE() //or CONVERT(VARCHAR(10), GETDATE(), 110)

Is there an equivalent to sysdate-1/24 in SQL server?

I've tried looking around for this but I can't find an answer that seems to work with the code I'm using. Basically, the below query searches on any result from the current date. I'm trying to make it so it will search only on the last hour.
In oracle I could do this using sysdate-1/24, is there a simple equivalent within SQL server? Bearing in mind I'm already using cast to get the current sysdate.
Select distinct m_record_server
from search_recording_file1
where tr_date_recorded >= cast(convert(varchar(10), getdate(), 110) as datetime)
and m_record_server is not null
You can use:
getdate() - 1.0/24
SQL Server allows you to use such arithmetic on datetime.
The more common way would be:
dateadd(hour, -1, getdate())
In your query, you do not need to cast to a string at all:
Select distinct m_record_server
from search_recording_file1
where tr_date_recorded >= getdate() - 1.0/24 and m_record_server is not null;
If you want the date that was there one hour ago (which seems to be the intent of the code, if not the rest of the question):
Select distinct m_record_server
from search_recording_file1
where tr_date_recorded >= cast(getdate() - 1.0/24 as date) and m_record_server is not null;

comparing between two datetimes

I have to compare datetimes using sql server 2012, that is, I have to see if certain datetimes from mytable1.start_time1 fall within the range of mytable2.start_time2 and mytable2.end_time2. By the datetime I mean the format of yyyy-mm-dd hh:mm:ss, and I can ignore the time.
What I do (and don't succeed) is as follows:
Select CUSTOMER_IDENTITY_NUMBER, a.CREATE_DATE, b.CREATE_DATE, b.END_DATE
from [mytable1]a
join [mytable2]b
on a.CUSTOMER_FK=b.CUSTOMER_PK
where cast(a.CREATE_DATE as date) not between cast(b.CREATE_DATE as date) and cast(b.END_DATE as date)
and cast(a.CREATE_DATE as date)<>cast(b.CREATE_DATE as date)
and cast(a.CREATE_DATE as date)<>cast(b.END_DATE as date)
Well, it doesn't work - the a.create_date returned does fall between the two other dates. Does anyone have an idea?
Thanks a bunch!
Try using a slightly different condition. I don't quite understand
the logical condition you used. Seems you got it incorrect.
select CUSTOMER_IDENTITY_NUMBER, a.CREATE_DATE, b.CREATE_DATE, b.END_DATE
from [mytable1]a
join [mytable2]b
on a.CUSTOMER_FK=b.CUSTOMER_PK
where
cast(a.CREATE_DATE as date) >= cast(b.CREATE_DATE as date)
and
cast(a.CREATE_DATE as date) <= cast(b.END_DATE as date)

DATEPART not working like i think it must

select *
from Advertisements
where DepartureDate < DATEPART('dd.mm.yy', '09.10.2010');
but i get
Msg 1023, Level 15, State 1, Line 1
Invalid parameter 1 specified for datepart.
in plsql is this very simple here is so complicated...
Can someone tell me please how can i get all dates that are smaller than today.
You can use this to get the current date:
CONVERT(date, GETDATE())
See the documentation.
Can someone tell me please how can i get all dates that are smaller than today.
SELECT *
FROM Advertisements
WHERE DepartureDate < CONVERT(date, GETDATE())
You seem to be confusing DATEPART with FORMAT_DATE (which does not exist anyway).
DATEPART extracts certain part of a date. Exactly one part.
Dates that are smaller than today are < dbo.CropTime(getdate()), where CropTime is a function which can be written in different ways (such as those described in this question).
Or, in case you are using SQL Server 2008, it's as simple as < cast(getdate() as date).
Would that code really work in PL/SQL? The DATEPART in T-SQL function is used to extract individual portions of a date.
This will get you all the dates before now.
select * from Advertisements where DepartureDate < getdate()
If you're planning to hardcode the date (as your sample code suggests), you just need to format in a way that SQL Server will understand. eg.
select * from Advertisements where DepartureDate < '2010-10-09'
I've been told that date format works on every server regardless of its localization settings. It's certainly worked on every server I've tried it on - but I'm happy to be overruled :-)
What you are looking for I think is
select *
from Advertisements
where DepartureDate < Convert(Date, '09.10.2010', 102)
or possibly
SELECT *
FROM Advertisements
WHERE DepartureDate < Cast(CURRENT_TIMESTAMP as date)
DatePart is used for getting components of the date such as the month, year or day. To get dates that are smaller (older) than now I would do this.
select * from Advertisements where DepartureDate < GetDate();
If I wanted Departure dates that were yesterday or before I could do this.
select * from Advertisements where DepartureDate < Convert(DateTime,Convert(Char(10),GetDate(),121));
or
select * from Advertisements where DepartureDate < Convert(DateTime,floor(convert(int,GetDate())))

SQL Server: Get data for only the past year

I am writing a query in which I have to get the data for only the last year. What is the best way to do this?
SELECT ... FROM ... WHERE date > '8/27/2007 12:00:00 AM'
The following adds -1 years to the current date:
SELECT ... From ... WHERE date > DATEADD(year,-1,GETDATE())
I found this page while looking for a solution that would help me select results from a prior calendar year. Most of the results shown above seems return items from the past 365 days, which didn't work for me.
At the same time, it did give me enough direction to solve my needs in the following code - which I'm posting here for any others who have the same need as mine and who may come across this page in searching for a solution.
SELECT .... FROM .... WHERE year(*your date column*) = year(DATEADD(year,-1,getdate()))
Thanks to those above whose solutions helped me arrive at what I needed.
Well, I think something is missing here. User wants to get data from the last year and not from the last 365 days. There is a huge diference. In my opinion, data from the last year is every data from 2007 (if I am in 2008 now). So the right answer would be:
SELECT ... FROM ... WHERE YEAR(DATE) = YEAR(GETDATE()) - 1
Then if you want to restrict this query, you can add some other filter, but always searching in the last year.
SELECT ... FROM ... WHERE YEAR(DATE) = YEAR(GETDATE()) - 1 AND DATE > '05/05/2007'
The most readable, IMO:
SELECT * FROM TABLE WHERE Date >
DATEADD(yy, -1, CONVERT(datetime, CONVERT(varchar, GETDATE(), 101)))
Which:
Gets now's datetime GETDATE() = #8/27/2008 10:23am#
Converts to a string with format 101 CONVERT(varchar, #8/27/2008 10:23am#, 101) = '8/27/2007'
Converts to a datetime CONVERT(datetime, '8/27/2007') = #8/27/2008 12:00AM#
Subtracts 1 year DATEADD(yy, -1, #8/27/2008 12:00AM#) = #8/27/2007 12:00AM#
There's variants with DATEDIFF and DATEADD to get you midnight of today, but they tend to be rather obtuse (though slightly better on performance - not that you'd notice compared to the reads required to fetch the data).
Look up dateadd in BOL
dateadd(yy,-1,getdate())
GETDATE() returns current date and time.
If last year starts in midnight of current day last year (like in original example) you should use something like:
DECLARE #start datetime
SET #start = dbo.getdatewithouttime(DATEADD(year, -1, GETDATE())) -- cut time (hours, minutes, ect.) -- getdatewithouttime() function doesn't exist in MS SQL -- you have to write one
SELECT column1, column2, ..., columnN FROM table WHERE date >= #start
I, like #D.E. White, came here for similar but different reasons than the original question. The original question asks for the last 365 days. #samjudson's answer provides that. #D.E. White's answer returns results for the prior calendar year.
My query is a bit different in that it works for the prior year up to and including the current date:
SELECT .... FROM .... WHERE year(date) > year(DATEADD(year, -2, GETDATE()))
For example, on Feb 17, 2017 this query returns results from 1/1/2016 to 2/17/2017
For some reason none of the results above worked for me.
This selects the last 365 days.
SELECT ... From ... WHERE date BETWEEN CURDATE() - INTERVAL 1 YEAR AND CURDATE()
The other suggestions are good if you have "SQL only".
However I suggest, that - if possible - you calculate the date in your program and insert it as string in the SQL query.
At least for for big tables (i.e. several million rows, maybe combined with joins) that will give you a considerable speed improvement as the optimizer can work with that much better.
argument for DATEADD function :
DATEADD (*datepart* , *number* , *date* )
datepart can be: yy, qq, mm, dy, dd, wk, dw, hh, mi, ss, ms
number is an expression that can be resolved to an int that is added to a datepart of date
date is an expression that can be resolved to a time, date, smalldatetime, datetime, datetime2, or datetimeoffset value.
declare #iMonth int
declare #sYear varchar(4)
declare #sMonth varchar(2)
set #iMonth = 0
while #iMonth > -12
begin
set #sYear = year(DATEADD(month,#iMonth,GETDATE()))
set #sMonth = right('0'+cast(month(DATEADD(month,#iMonth,GETDATE())) as varchar(2)),2)
select #sYear + #sMonth
set #iMonth = #iMonth - 1
end
I had a similar problem but the previous coder only provided the date in mm-yyyy format. My solution is simple but might prove helpful to some (I also wanted to be sure beginning and ending spaces were eliminated):
SELECT ... FROM ....WHERE
CONVERT(datetime,REPLACE(LEFT(LTRIM([MoYr]),2),'-
','')+'/01/'+RIGHT(RTRIM([MoYr]),4)) >= DATEADD(year,-1,GETDATE())
Here's my version.
YEAR(NOW())- 1
Example:
YEAR(c.contractDate) = YEAR(NOW())- 1
For me this worked well
SELECT DATE_ADD(Now(),INTERVAL -2 YEAR);
If you are trying to calculate "rolling" days, you can simplify it by using:
Select ... FROM ... WHERE [DATE] > (GETDATE()-[# of Days])