Corresponding column value to MAX() of a different column?

  • Hopefully I can explain properly what I'm trying to do here. I'm not very experienced in SQL so maybe the solution is easier than I'd expect.

    So let's say I have a Company table, so we have Company Names and UniqueIDs.

    Then I have a table called Meetings, and this contains a Meeting Date, a Meeting Type, and the UniqueID for the Company the meeting was with.

    So I want to select the most recent meeting with each company, so my three columns are Company, Meeting Date, and Meeting Type.

    So I can join these tables, group by Company (its UniqueID), and use MAX(MeetingDate). This gives me the company and the date of the most recent meeting. Is there an easy way to pull in the MeetingType for whichever the MAX(MeetingDate) turned out to be?

    I appreciate any help I can get, thanks!

  • Give this a try:

    -- Then I have a table called Meetings, and this contains a Meeting Date, a Meeting Type, and the UniqueID for the Company

    -- the meeting was with.

    with BaseMeetings as (

    select

    MeetingDate,

    MeetingType,

    CompanyId,

    row_number() over (partition by CompanyId order by MeetingDate desc) rn

    from

    dbo.Meetings

    )

    select

    CompanyId,

    MeetingType,

    MeetingDate

    from

    BaseMeetings

    where

    rn = 1;

  • Extremely helpful, I still have much to learn.

  • Glad to help.

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply