SQL Server 2008 - 使用多列中的值替换代码

时间:2011-11-30 12:22:21

标签: sql sql-server-2008 select left-join

我有以下表格:

TABLE_1:

Value_ID     Value_Code_1      Value_Code_2       Value_Code_3
1            465               325                129

TABLE_2:

ID          Text
465         this is a value
325         this value is a different one
129         hello world

我需要使用Table_2中的Text替换Table_1中的代码。我想解决这个问题的方式似乎很长很多毛,是否有更快,更好的方法来做到这一点?我必须在大约40列中执行此操作,而不是在我的示例中执行此操作。

我的代码:

Select
    first.ID,
    first.string_value,
    second.string_value,
    third.string_value
from
(
    Select
        a.ID,
        b.text as string_value
    From
        table_1 a
        left join
        table_2 b
        on a.Value_Code_1 = b.ID
) first

left join on first.id = second.id

(
    Select
        a.ID,
        b.text as string_value
    From
        table_1 a
        left join
        table_2 b
        on a.Value_Code_2 = b.ID
) second

left join on first.id = third.id
(
    Select
        a.ID,
        b.text as string_value
    From
        table_1 a
        left join
        table_2 b
        on a.Value_Code_2 = b.ID
) third

谢谢。

2 个答案:

答案 0 :(得分:2)

你可以更简单地做到这一点:

Select
    Table_1.ID,
    v1.Text,
    v2.Text,
    v3.Text
FROM Table_1
LEFT JOIN Table_2 v1 ON Table_1.Value_code_1 = v1.id
LEFT JOIN Table_2 v2 ON Table_1.Value_code_2 = v2.id
LEFT JOIN Table_2 v3 ON Table_1.Value_code_3 = v3.id;

您仍然需要为所有40列进行此操作。

答案 1 :(得分:0)

我不知道这是否比40次加入更多或更少,或者是否更容易,但是可以考虑......

SELECT
  Table1.Value_ID,
  MAX(CASE WHEN Table1.Value_Code_1 = Table2.ID THEN Table2.Text ELSE NULL END) AS Text1,
  MAX(CASE WHEN Table1.Value_Code_2 = Table2.ID THEN Table2.Text ELSE NULL END) AS Text2,
  MAX(CASE WHEN Table1.Value_Code_3 = Table2.ID THEN Table2.Text ELSE NULL END) AS Text3,
  MAX(CASE WHEN Table1.Value_Code_4 = Table2.ID THEN Table2.Text ELSE NULL END) AS Text4,
  etc
FROM
  Table1
LEFT JOIN
  Table2
    ON Table2.ID = Table1.Value_Code_1
    OR Table2.ID = Table1.Value_Code_2
    OR Table2.ID = Table1.Value_Code_3
    OR Table2.ID = Table1.Value_Code_4
GROUP BY
  Table1.Value_ID


如果你要对Table1进行规范化,那就更容易了......

New Table1:
> Value_ID,
> Column_ID,
> Value_Code

New SQL:
SELECT
  Table1.Value_ID,
  MAX(CASE WHEN Table1.Column_ID = 1 THEN Table2.Text ELSE NULL END) AS Text1,
  MAX(CASE WHEN Table1.Column_ID = 2 THEN Table2.Text ELSE NULL END) AS Text2,
  MAX(CASE WHEN Table1.Column_ID = 3 THEN Table2.Text ELSE NULL END) AS Text3,
  MAX(CASE WHEN Table1.Column_ID = 4 THEN Table2.Text ELSE NULL END) AS Text4,
  etc
FROM
  Table1
LEFT JOIN
  Table2
    ON Table2.ID = Table1.Value_Code
GROUP BY
  Table1.Value_ID

(这类似于使用UNPIVOT的答案)