我在表中有一個下面的列值
Destination
DELLKO
DELBOM
DELVGA
BOMIXY
等等
和另一個包含以下資料的表
表名——CITY
CityName Code
Agartala IXA
Agatti AGX
Agra AGR
Akola AKD
Allahabad IXD
Aurangabad IXU
Siliguri IXB
Bareilly BEK
Lucknow LKO
DELHI DEL
BOM MUMBAI
等等
現在我想要這樣的輸出
DELHI|Lucknow
DELHI|MUMBAI
在表 CITY 的幫助下,即無論目標列有 DEL,它都應該替換為 DELHI 附加管道符號并搜索 LKO 并附加 LUCKNOW。
uj5u.com熱心網友回復:
如果城市代碼多于 3 個字母或少于 3 個字母,請告訴我。現在,讓我們假設代碼只有 3 個字母。試試這個:
-- Temp tables for example:
--========================================================
if OBJECT_ID('tempdb..#Abbreviation') is null
begin
create table #Abbreviation(
destination char(6)
);
end
else
begin
truncate table #Abbreviation;
end;
if OBJECT_ID('tempdb..#City') is null
begin
create table #City(
cityName varchar(50)
, code char(3)
);
end
else
begin
truncate table #City;
end;
-- Query:
--========================================================
with cte_main as(
select
left(destination, 3) partOneCode
, right(destination, 3) partTwoCode
from #Abbreviation
)
, cte_preSet as(
select
main.partTwoCode
, sub.cityName cityNameOne
from cte_main main
inner join
#City sub
on main.partOneCode = sub.code
)
select
main.cityNameOne '|' sub.cityName
from cte_preSet main
inner join
#City sub
on main.partTwoCode = sub.code;
uj5u.com熱心網友回復:
在目的地代碼上兩次加入 CITY。
SELECT CONCAT(city1.CityName,'|',city2.CityName) AS Destination
FROM Destinations dest
LEFT JOIN CITY city1 ON city1.Code = LEFT(dest.Destination, 3)
LEFT JOIN CITY city2 ON city2.Code = RIGHT(dest.Destination, 3)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/387480.html
標籤:查询语句
上一篇:使用游標為2個表插入行
