使用“REPLACE”匹配列名,然后连接表 - SSMS

时间:2013-02-07 21:35:42

标签: sql ssms

我有下表 - 称之为Table1:

SIMULATION  PRODUCT               PERIOD    OUTPUT_OL_EstRes
0           USSIC_Aviation        2012Q3    25787698
0           Avemco_Aviation       2012Q3    13374366
0           HC_Houston_Aviation   2012Q3    41626488
0           Other_Aviation        2012Q3    700829
0           Disability            2012Q3    8566175

我正在尝试加入下表 - 称之为Table2:

RptLOB                RptLOBPrintOrder  RptSegt
USSIC Aviation        1                 US Property & Casualty
Avemco Aviation       2                 US Property & Casualty
HC Houston Aviation   3                 US Property & Casualty
Other Aviation        4                 US Property & Casualty
Disability            5                 US Property & Casualty

使用以下代码:

select a.SIMULATION, REPLACE(a.PRODUCT,'_',' ') as PRODUCT, a.PERIOD, a.OUTPUT_OL_EstRes , b.RptLOBPrintOrder, b.RptSegt
from Table1 as a
left join Table2 as b
on a.PRODUCT=b.RptLOB

我在RptLOBPrintOrder和RptSegt列上得到NULL值(除了值Disability,因为我不必去除下划线)。我确保摆脱“_”,所以我不太清楚为什么会发生这种情况。输出表如下:

SIMULATION  PRODUCT                 PERIOD  OUTPUT_OL_EstRes    RptLOBPrintOrder    RptSegt
0           USSIC Aviation          2012Q3  25787698            NULL                NULL
0           Avemco Aviation         2012Q3  13374366            NULL                NULL
0           HC Houston Aviation     2012Q3  41626488            NULL                NULL
0           Other Aviation          2012Q3  700829              NULL                NULL
0           Disability              2012Q3  8566175             5                   US Property & Casualty

任何帮助将不胜感激!有没有更好的方法呢?

1 个答案:

答案 0 :(得分:1)

查询:

<强> SQLFIDDLEXample

SELECT a.SIMULATION,
       REPLACE(a.PRODUCT,'_',' ') AS PRODUCT,
       a.PERIOD,
       a.OUTPUT_OL_EstRes ,
       b.RptLOBPrintOrder,
       b.RptSegt
FROM Table1 AS a
LEFT JOIN Table2 AS b ON REPLACE(a.PRODUCT,'_',' ')=b.RptLOB

结果:

| SIMULATION |             PRODUCT | PERIOD | OUTPUT_OL_ESTRES | RPTLOBPRINTORDER |                RPTSEGT |
------------------------------------------------------------------------------------------------------------
|          0 |      USSIC Aviation | 2012Q3 |         25787698 |                1 | US Property & Casualty |
|          0 |     Avemco Aviation | 2012Q3 |         13374366 |                2 | US Property & Casualty |
|          0 | HC Houston Aviation | 2012Q3 |         41626488 |                3 | US Property & Casualty |
|          0 |      Other Aviation | 2012Q3 |           700829 |                4 | US Property & Casualty |
|          0 |          Disability | 2012Q3 |          8566175 |                5 | US Property & Casualty |