how to link between two tables

SPWGUT 121 Reputation points
2022-04-18T08:00:13.69+00:00

Hi,i want to select cities groupping by countries ,Any suggestions?

My code
create table dbo.Countries ( CountryID int, Country nvarchar(255) )
insert into dbo.Countries ( CountryID, Country )
values ( 1, N'Russia' ), ( 2, N'USA' ), ( 3, N'Germany' )
, ( 4, N'France' ), ( 5, N'Italy' ), ( 6, N'Spain' )

create table dbo.Cities ( CityID int, CountryID int, City nvarchar(255) )
insert into dbo.Cities ( CityID, CountryID, City )
values ( 1, 1, N'Moscow' ), ( 2, 1, N'St. Petersburg' ), ( 3, 1, N'Yekaterinburg' )
, ( 4, 1, N'Novosibirsk' ), ( 5, 1, N'Samara' ), ( 6, 2, N'Chicago' )
, ( 7, 2, N'Washington' ), ( 8, 2, N'Atlanta' ), ( 9, 3, N'Berlin' )
, ( 10, 3, N'Munich' ), ( 11, 3, N'Hamburg' ), ( 12, 3, N'Bremen' )
, ( 13, 4, N'Paris' ), ( 14, 4, N'Lyon' ), ( 15, 5, N'Milan' )
go

Sorry, forgot to put the desired result, here is the result I requested.
1 Russia 1 1 Moscow
1 Russia 2 1 St. Petersburg
1 Russia 3 1 Yekaterinburg
1 Russia 4 1 Novosibirsk
1 Russia 5 1 Samara

Thanks in advance..

Developer technologies | Transact-SQL
SQL Server | Other
0 comments No comments
{count} votes

Accepted answer
  1. LiHong-MSFT 10,056 Reputation points
    2022-04-18T08:10:26.237+00:00

    Hi @SPWGUT
    You just need a simple join,check this:

        SELECT *  
        FROM dbo.Countries A JOIN dbo.Cities B ON A.CountryID=B.CountryID  
        WHERE A.CountryID =1  
    

    Output:
    193794-image.png

    Best regards,
    LiHong


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful

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.