All fields from MS SQL table A and only the top from tableB

Hi Experts,

My MS SQL tables A and B have one to many relation. One entry in table A can have multiple related entries in table B.

With the query below I get a list of records so that works.

Select A.accountname, B.actiondate from B inner join A on A.account=B.account

Open in new window


The output is like:

accountname      actieondate
JohnD      2013-2-12
JohnD      2013-2-16
JohnD      2013-3-24
MaryC      2013-5-24
GeorgeB      2013-3-11
GeorgeB      2013-6-21


But I would like to get only the latest action dates only like in the output example below

accountname      actieondate
JohnD      2013-3-24
MaryC      2013-5-24
GeorgeB      2013-6-21
LVL 1
SteynskAsked:
Who is Participating?
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.

Louis01Commented:
select A.accountname
     , max(B.actiondate) as actiondate
  from B 
        inner join A 
    on A.account=B.account
 group by A.accountname

Open in new window

0
HuaMin ChenProblem resolverCommented:
Try
with cte as
(Select B.actiondate, A.accountname,ROW_NUMBER() OVER(PARTITION BY b.actiondate ORDER BY A.accountname desc) rn from B inner join A on A.account=B.account)
select actiondate,accountname
from cte
where rn=1;

Open in new window

0

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
Barry CunneyCommented:
Select
A.accountname
,MAX(B.actiondate) ActionDate
from B
inner join A on A.account=B.account
GROUP BY A.accountname
ORDER BY A.accountname
0
SteynskAuthor Commented:
Thank you Hua Min Chen it works excelently
0
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
Microsoft SQL Server

From novice to tech pro — start learning today.