在SQL Server中映射两个表值

时间:2016-07-04 07:33:38

标签: sql sql-server sql-server-2008

我有一张下表显示

Code    Budhol           COCODE      BEN    FieldNameNew
1      MEDICAL CENTRE   SA          CITY1    PFEmployee
5      MEDICAL CENTRE   SA          CITY1    PF
21     UKTI             UKTI        CITY1    PFEmployee
22     UKTI             UKTI        CITY2    PFEmployee
25     UKTI             UKTI        CITY1    PF
29     UKTI             UKTI        CITY2    PFEmployee
33     UKTI             UKTI        CITY1    PFEmployee

存储映射的其他表格显示在

下面
FieldName   ComboValue        Code
COCODE       SA                36
COCODE       UKTI              65
BUDHOL       MEDICAL CENTRE    652531
BUDHOL       UKTI              14102
BEN          CITY1             14251
BEN          CITY2             12584
PFEmployee   PFEmployee        7785
PF           PF                7789

对于 FieldNameNew ,Db中只有一个可用的映射

这是必需的最终输出

Code    Budhol           COCODE      BEN    FieldNameNew
1      652531             36        14251    7785
5      652531             36        14251    7789
21     14102              65        14251    7785
22     14102              65        12584    7785
25     14102              65        14251    7789
29     14102              65        12584    7785
33     14102              65        14251    7785

我曾尝试使用Case,但它没有进行优化我必须硬编码数据,但它是动态的

1 个答案:

答案 0 :(得分:1)

你可以这样试试,

SELECT A.code
    ,Bud.Code AS Budho1
    ,Co.Code AS COCODE
    ,Ben.Code AS BEN
    ,F.Code AS FieldNameNew
FROM TableA A
INNER JOIN TableB Bud ON A.Budho1 = Bud.ComboValue
    AND Bud.FieldName = 'BUDHOL'
INNER JOIN TableB Co ON A.COCODE = Co.ComboValue
    AND Co.FieldName = 'COCODE'
INNER JOIN TableB Ben ON A.BEN = Ben.ComboValue
    AND Ben.FieldName = 'BEN'
INNER JOIN TableB F ON A.FieldNameNew = F.ComboValue