Link to home
Start Free TrialLog in
Avatar of qwertq
qwertq

asked on

SQL this day one year ago

ok i am working on a sql and having problems....

what i want to do is to select all rows that are from this day one year ago. here is my query:

SELECT *
FROM orders
WHERE
TO_DAYS(NOW()) = TO_DAYS(orderDate) AND YEAR(date_add(NOW(), interval '-1' year)) = YEAR(orderDate)

the year must remain seperate from the day.

thanks!
Avatar of Batalf
Batalf
Flag of United States of America image

One option is to create the date one year ago as a variable and use that in your query

example:

<?
$oneYearAgo = (date("Y")-1)."-".date("m-d 00:00:00"); // Creates a datetime
$sql = "select * from orders where orderDate>'$oneYearAgo'");

?>

This is if orderDate is a datetime (YYYY-MM-DD HH:MI:SS).

Batalf
Avatar of German_Rumm
German_Rumm

Hi qwertq,

Here you go:
    SELECT *, DAY (orderDate), MONTH(orderDate) FROM orders WHERE DATE_ADD(NOW(), INTERVAL -1 YEAR) = orderDate

---
German Rumm.
Avatar of qwertq

ASKER

baltf: i was really hoping to get the work done in the query.

ger: that did not seem to work. here is what i tried:
select * FROM phoneCart WHERE DATE_ADD(NOW(), INTERVAL -1 YEAR) = orderDate

also, is there no command for current day number in sql? that would really work best for me, because this is part of a function that also looks up week last year, year to date and month to date, all with same function to eliminate duplicate coding.
Avatar of qwertq

ASKER

maybe something similar to DAYOFYEAR(NOW()), is there a DAYOFMONTH?
Avatar of qwertq

ASKER

i am high. there is
try looking at the DATE_FORMAT function...
it provides a number of ways of parsing a date
e.g. DATE_FORMAT(mydate,"%Y")

the function for the current date is CURDATE(), time is CURTIME(), both in tandem is NOW()

so if you want find records that are a year old...

SELECT * FROM phoneCart WHERE ( DATE_FORMAT(CURDATE(),"%Y") = DATE_FORMAT(mydate,"%Y") + 1) AND
(DATE_FORMAT(CURDATE(),"%d") = DATE_FORMAT(mydate,"%d"))



Different databases use different Date/Time functions - which one are you using?

--saddy1--
Avatar of qwertq

ASKER

i used DAYOFMONTH...
good point... I usually assume MySQL + PHP.  The format he's using looks more like T-SQL
ASKER CERTIFIED SOLUTION
Avatar of saddy1
saddy1

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial