Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Identify unused codes

Author  Topic 

kangle
Starting Member

5 Posts

Posted - 2013-04-17 : 09:39:51
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
Master Smack Fu Yak Hacker

3873 Posts

Posted - 2013-04-17 : 09:45:39
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

5 Posts

Posted - 2013-04-17 : 09:59:48
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
Master Smack Fu Yak Hacker

3873 Posts

Posted - 2013-04-17 : 10:38:34
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
   

- Advertisement -