I'm having some trouble with my SQL query. I got this table:
insert into Table1 (date, personssn)
insert ('2012-01-21 12:01:33', '123456789');
insert into Table1 (date, personssn)
insert ('2012-02-22 12:01:33', '123456789');
The problem is that I want to select the personssn who have a date CLOSEST to the current date. I've been working with "CURDATE()" but can't seem to get it to work. Anyone that can help me in the right direction?
Thanks.
Here we will see, SQL Query to compare two dates. This can be easily done using equals to(=), less than(<), and greater than(>) operators. In SQL, the date value has DATE datatype which accepts date in 'yyyy-mm-dd' format. To compare two dates, we will declare two dates and compare them using the IF-ELSE statement.
Two Ways to Use DATEDIFF() Function in SQL: It may return the result into the table of data. Use of DATEDIFF() to find the differences between two date values. In this type, the DATEDIFF() function is used to find the number of days or years or any other count between the two DATE values.
ABS() function : This function in SQL Server is used to return the absolute value of a specified number. Absolute value is used for depicting the distance of a number on the number line from 0. The direction of the number from zero is not considered since the absolute value of a number is never negative.
To get the current date and time in SQL Server, use the GETDATE() function. This function returns a datetime data type; in other words, it contains both the date and the time, e.g. 2019-08-20 10:22:34 . (Note: This function doesn't take any arguments, so you don't have to put anything in the brackets.)
select *
from Table1
order by
abs(now() - date) desc
limit 1
Use datediff. It returns the Difference between two dates. However, you can have dates before and after today in your database. That's why you need ABS() without it the smallest value would be selected first, but we want the value closest to 0. IE a Date-Difference of 3 is “bigger” than -250, but 3 days off is closer. That is why you use the absolute value.
SELECT t1.date, t1.personssn
FROM Table1 AS t1
ORDER BY ABS(DATEDIFF(t1.date, NOW())) ASC
LIMIT 5
Try this with simple order by :
SELECT date,personssn FROM Table1 ORDER BY date desc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With