T-SQL Help - INNER JOIN WITH MAX DATE

Hi - I need help composing a t-sql statement.

I need to join two table.  One table (Table A) has a list of component with a unique ID for each component.  The other table (Table B) stores the date that that component was ordered.

I need to run a report that shows each component and the last time the component was ordered.  How can I do this.

Table A

ID |  ComponentName |
1  |  Television                |
2  | Radio                        |
3  | Computer                 |


Table B

PK |  ID   |  Date Used  |
1    |  2     |  5/6/2015  |
2    |  2     | 6/1/2015    |
3    |  3      |  1/1/2015  |
4    |  3      | 3/1/2015   |
5    |  1     |  7/1/2015   |


What I want my report to look like:

Component Name   |  Date Last Used
Radio                          |   6/1/2015
Computer                   |  3/1/2015
Television                    | 7/1/2015

Thank you in advance for your help.
cdemott33Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Steve WalesSenior Database AdministratorCommented:
select a.component_name, b.max_date
from TableA a
join 
(select id, max(Date_Used) as max_date from TableB group by id) b on a.id = b.id
order by <whatever you need>

Open in new window


If a component has never been issued, it won't appear in the report.

To remedy that and show date last used as null, change JOIN to LEFT JOIN

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Brian CroweDatabase AdministratorCommented:
SELECT A.ID, A.ComponentName, MAX(B.[Date Used]) AS LastUsedDate
FROM TableA AS A
LEFT OUTER JOIN TableB AS B
   ON A.ID = B.ID
GROUP BY A.ID, A.ComponentName
cdemott33Author Commented:
Worked perfectly.  Thank you.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Query Syntax

From novice to tech pro — start learning today.