我喜欢将此视为 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
它可能会有点混乱/难以理解。此外,必须知道在 CityName 和 Country.Id 之间添加的(任意)字符串在 CITYNAME 中不存在。最后,我提供的代码没有正确解释任何空值。我会将 City.CityName 和 Country.Id 的每个实例替换为 isnull(City.CityName,'') 和 isnull(Country.Id,'')。