2

I have a table with a list of Client No's, ID etc & there are many Clients with different ID's. I need to pull out the MAX ID No. for each Client, e.g.

ClientNo: 1500 has 3 ID's - the maximum in the ID field is the one I need!

UPDATE: This works:

SELECT MP.ClientID, MP.SequenceID
FROM  TABLENAME MP
INNER JOIN (
SELECT ClientID, MAX(SequenceID) SequenceID
FROM  TABLENAME
GROUP BY ClientID
) b on MP.ClientID = b.ClientID AND MP.SequenceID = b.SequenceID

BUT....

I need to link the table to many others to pull in other data, where do I insert the left joins to these tables please?

1
  • 1
    Hint: GROUP BY. Commented Aug 7, 2019 at 15:59

2 Answers 2

2

I am assuming you have multiple same client (numbers) with different IDs and for each client (number) you have to get the maximum ID. You may do the following:

select client_number, max(ID) from client group by client_number;

Depending on your need tweak this query.

Sign up to request clarification or add additional context in comments.

3 Comments

SELECT MP.ClientID, MP.SequenceID FROM [5QDC_BAK].[dbo].[MonthlyPlannerApp] MP INNER JOIN ( SELECT ClientID, MAX(SequenceID) SequenceID FROM [5QDC_BAK].[dbo].[MonthlyPlannerApp] GROUP BY ClientID ) b on MP.ClientID = b.ClientID AND MP.SequenceID = b.SequenceID
but I need to insert some left joins to other tables do you know where I need to do this please?
After you finished your inner join, start the left outer join assuming that the left side is the primary side. It looks like: select a.x, a.y from a inner join b on a.id=b.id left outer join c on a.id=c.id;
0

You may want to do this:

SELECT MP.ClientID, b.DesiredValue
FROM  TABLENAME MP
INNER JOIN (
            SELECT ClientID, DesiredValue, ROW_NUMBER () OVER (PARTITION BY ClientID order by SequenceID desc) As RecentRN
            FROM  TABLENAME
            ) b 
        on MP.ClientID = b.ClientID AND b.RecentRN = 1

or

SELECT MP.ClientID, b.DesiredValue
FROM  TABLENAME MP
INNER JOIN (
            SELECT ClientID, DesiredValue,ROW_NUMBER () OVER (PARTITION BY ClientID order by SequenceID desc) As RecentRN
            FROM  TABLENAME
            ) b 
        on MP.ClientID = b.ClientID
Where b.RecentRN = 1

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.