tags:

views:

127

answers:

4

I'm trying to get the products that havn't been made in the last 2 years. I'm not that great with SQL but here's what i've started with and it doesn't work.

Lets say for this example that my schema looks like this

prod_id, date_created, num_units_created.

I'll take any advice i can get.

select id, (select date from table
            where date <= sysdate - 740) older,
           (select date from table
            where date >= sysdate - 740) newer 
from table 
where newer - older

I'm not being clear enough.

Basically i want all products that havn't been produced in the last 2 years. Whenever a product is produced, a line gets added. So if i just did sysdate <= 740, it would only give me all the products that were produced from the beginning up til 2 years ago.

I want all products that have been produced in the at least once, but not in the last 2 years.

I hope that clears it up.

+3  A: 

I'd use SQL's dateadd function.

where date < dateadd(year,-2,getdate())

would be a where clause that would select records with date less than 2 years from the current date.

Hope that helps.

EDIT: If you want to go by days, use dateadd(d,-740,getdate())

Aaron
DATEADD doesn't exist in Oracle, `ADD_MONTHS(SYSDATE, -24)` is equivalent.
OMG Ponies
Fair enough. I saw the SQL tag in the question. Thanks.
Aaron
@Aaron: That's one little behavior I detested about IBM in the day and detest about Microsoft when it happens: co-opting common words and phrases to designate specific products. There's the IBM Personal Computer, Microsoft SQL Server, two different varieties of Disk Operating System (hint: the one I was originally familiar with ran on 360s), and more.
David Thornley
A: 

Maybe something like this?

select id, date
from table
where date <= (sysdate - 730);
Andy White
Guess this would return ids that have been produced more than 2 years ago, but not remove those that have not been produced within the last two years.
Peter Lang
A: 
SELECT id FROM table WHERE date + (365*2) <= sysdate;

Use SELECT id, date, other, columns ... if you need to get them at the same time.

Roger Pate
Guess this would return ids that have been produced more than 2 years ago, but not remove those that have not been produced within the last two years. Also be careful with leap years.
Peter Lang
+5  A: 

GROUP BY with HAVING

select id, max(date)
from table
group by id
having max(date) < add_months(sysdate,-24)
Gary
+1 Both correct and the most simple solution.
APC
This seems like it'll work. Can you explain to me how it works?You are selecting the most recent date where the most recent date is less than 2 years ago? Should that be select id,max(date) from table group by id having date < add_months(sysdate, -24)??Can you explain why that is wrong?
Catfish
Because you want to know when the LATEST date is before two years ago. The max is the latest date.
Gary