Get the maximum of Country

NNP 20 Reputation points
2023-09-27T07:18:11.8233333+00:00

I have a table.

create table Company
( 
  CompanyID char(10),
  Country varchar(50),
  EstYear int
);

insert into Company values('A','USA',2016)
insert into Company values('A','USA',2017)
insert into Company values('A','UK',2018)
insert into Company values('A','USA',2019)
insert into Company values('A','Japan',2020)
insert into Company values('A','Japan',2021)
insert into Company values('A','USA',2022)
insert into Company values('B','USA',2016)
insert into Company values('B','UK',2017)
insert into Company values('B','UK',2018)
insert into Company values('B','Brazil',2019)
insert into Company values('B','Brazil',2020)
insert into Company values('B','Spain',2021)
insert into Company values('B','Brazil',2022)

I want to get this result.

CompanyID Country
A USA
B Brazil

Thanks.

SQL Server | Other
{count} votes

Answer accepted by question author
  1. Anonymous
    2023-09-27T07:34:03.5233333+00:00

    Hi @NNP

    If I understand correctly, you can try this query.

    ;with CTE as (
      select CompanyId,Country,
        rank()over(partition by CompanyId order by Count(*) desc) as num
      from Company group by CompanyId,country)
    select CompanyId,Country from CTE where num = 1;
    

    Output:

    User's image

    Best regards,

    Percy Tang

    1 person found this answer helpful.
    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Viorel 125.7K Reputation points
    2023-09-27T12:26:20.31+00:00

    The next query gives your results, maybe accidentally:

    select x.CompanyID, x.Country
    from Company x
    left join Company y on y.CompanyID = x.CompanyID and y.EstYear > x.EstYear
    where y.CompanyID is null
    
    1 person found this answer helpful.
    0 comments No comments

  2. NNP 20 Reputation points
    2023-09-28T08:36:39.1966667+00:00

    Thanks all.

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.