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
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
13,670 questions
{count} votes

Accepted answer
  1. PercyTang-MSFT 12,501 Reputation points Microsoft Vendor
    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 116.6K 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 Answers by the question author, which helps users to know the answer solved the author's problem.