如何在多个左连接中获取唯一值

How to get unique values in multiple left join

我有以下代码我必须连接 3 个表但是 Dest.Code 有重复的值。如何获得 Dest.Code 的唯一值?

我试过 DISTINCT 但没有用。

SELECT
   Dest.Code 
  ,City.CityName  
  ,Country.Id
FROM base.Dest
   Left join base.City
   On base.Dest.CityId = base.City.Id
   Left join base.Country 
   On base.City.CountryId = base.Country.Id

这是结果:但是ASA出现了两次。我只需要一次,不管是哪一次。

Code    CityName    Id          
ASA     Ardmore     1E-599-4E   
ASA     Miami       8B-203-4D   
WBG     Rome        9S-893-2E   
BMU     Leon        2B-103-8E   
SELECT
   Dest.Code 
  ,Dest.DestName 
  ,Dest.Code + ' ' + Dest.DestName as Destination
  ,Dest.Latitude
  ,Dest.Longitude
  ,Dest.CityId
  ,City.InternCityName 
  ,City.CityName 
  ,Country.CountryNameInt 
  ,Country.CountryName 
  ,Case 
     when Country.CountryName = 'Country' 
     then 'Local' 
     else 'Exterior' 
     end 
FROM DataBase.Destinations as Dest
INNER JOIN
(
    SELECT  DISTINCT Code,CityId FROM  DataBase.Destinations AS dest1 
)dest2

ON dest.CityId=dest2.CityId

Left join DataBase.Cities City
On Dest.CityId = City.Id

Left join DataBase.Countries Country
On City.CountryId = Country.Id

Note:- Sub Query is using for distinct value and inner join for common value only...

用一个新列将您的查询包装在 CTE 中,您将使用该列来过滤结果。
这个新列是用 ROW_NUMBER() window 函数生成的,由 Dest.Code:

WITH cte as (
  SELECT Dest.Code, City.CityName, Country.Id,
  ROW_NUMBER() OVER (PARTITION BY Dest.Code ORDER BY City.CityName, Country.Id) AS rn   
  FROM Dest
  LEFT JOIN City ON Dest.CityId = City.Id
  LEFT JOIN Country ON City.CountryId = Country.Id
)
SELECT Code, CityName, Id
FROM cte
WHERE rn = 1

我喜欢将其视为 CTE 或任何使用行号的创意替代品,但我对性能一无所知:

SELECT
   Dest.Code 
  ,max(City.CityName + ' ### ' + Country.Id)
FROM base.Dest
   Left join base.City
   On base.Dest.CityId = base.City.Id
   Left join base.Country 
   On base.City.CountryId = base.Country.Id
group by dest.code

这存在将 CityName 和 Country.Id 显示为单个输出列的问题。这可能是可以接受的——或者您可以使用 patindex、left 和 substring 将其拆分出来:

SELECT
   Dest.Code 
  ,left(max(City.CityName + ' ### ' + Country.Id),patindex('% ### %',max(City.CityName + ' ### ' + Country.Id))) CityName
  ,substring(max(City.CityName + ' ### ' + Country.Id),patindex('% ### %',max(City.CityName + ' ### ' + Country.Id)) + 5,len(max(City.CityName + ' ### ' + Country.Id))) Id
FROM base.Dest
   Left join base.City
   On base.Dest.CityId = base.City.Id
   Left join base.Country 
   On base.City.CountryId = base.Country.Id
group by dest.code

可以稍微理解一下messy/difficult。此外,必须知道在 CityName 和 Country.Id 之间添加的(任意)字符串不存在于 CITYNAME 中。 最后,我提供的代码没有正确说明任何空值。我会将 City.CityName 和 Country.Id 的每个实例替换为 isnull(City.CityName,'') 和 isnull(Country.Id,'').