SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Identify unused codes
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

kangle
Starting Member

2 Posts

Posted - 04/17/2013 :  09:39:51  Show Profile  Reply with Quote
New to working with SQL and databases for that matter so I could use some help. I have a table with 13 million records and need to identify codes that have not been used in the past five years. There are approximately 50,000 records in the code table. I think I need to perform some type of join between the two tables but I'm not sure how to proceed.

Thanks in advance.

James K
Flowing Fount of Yak Knowledge

3742 Posts

Posted - 04/17/2013 :  09:45:39  Show Profile  Reply with Quote
Is there a column in that table (or another table) that indicates when a code was last used? If you have, you could do something like this:
select
	code
from
	YourUsageTable
group by
	code
having
	max(usageDate) < dateadd(yy,-5,getdate());
Go to Top of Page

kangle
Starting Member

2 Posts

Posted - 04/17/2013 :  09:59:48  Show Profile  Reply with Quote
Hi James, thanks for responding. I follow the first part and that's where I got stuck. So I have table A which has the listing of all the unique codes and Table B which has the history of when the codes have been used. There are 50k records in A and 13mil in B. I actually need to perform two separate queries. Generate a listing of codes that haven't been used in the past five years and generate a listing of codes that have never been used at all.

This is what I started with...

SELECT [TableA].Code, [TableA].CodeDescription
from [TableA]
left join [TableB]
on [TableA].ID=[TableB].CodeID
Go to Top of Page

James K
Flowing Fount of Yak Knowledge

3742 Posts

Posted - 04/17/2013 :  10:38:34  Show Profile  Reply with Quote
Here is an example of how you can write the query. This query gives you both kinds. You can remove one or the other clause from the HAVING section to pick one type of the other. You can copy the code and run from an SSMS window to see how it behaves:
create table #A(id int);
create table #B(CodeId int, dt datetime) 

insert into #A values (1),(2),(3),(4),(5);
insert into #B values 
(1,'20120401'),(1,'20000101'),
(2,'20120501'),
(3,'20000307'),(3,'20041212');

select
	a.id,
	max(b.dt)
from
	#A a
	left join #B b on
		a.Id = b.CodeId
group by
	a.Id
having
	max(b.dt) < dateadd(yy,-5,getdate())
	or max(b.dt) is null  
drop table #A,#B;
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.11 seconds. Powered By: Snitz Forums 2000