【问题标题】:replace column values while searching from another table从另一个表中搜索时替换列值
【发布时间】:2022-01-21 14:05:21
【问题描述】:

我在表格中有一个以下列值

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

在 Table CITY 的帮助下,即目标列有 DEL 的地方,应将其替换为 DELHI 附加管道符号并搜索 LKO 并附加 LUCKNOW。

【问题讨论】:

  • 只需使用left(Destination,3)right(Destination,3)CITY 表连接您的表(2 个不同的连接)?
  • 您确定CITY 表中的'BOM'/'MUMBAI' 行吗?是否可以交换列值?

标签: tsql


【解决方案1】:

如果城市代码多于 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;

【讨论】:

    【解决方案2】:

    在目的地代码上加入 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)
    

    【讨论】:

      猜你喜欢
      • 2020-03-20
      • 2015-11-30
      • 2018-06-06
      • 2019-02-15
      • 1970-01-01
      • 1970-01-01
      • 2014-05-01
      • 1970-01-01
      相关资源
      最近更新 更多