SQL Server 2008 - 用多列中的值替换代码
我有以下表格:
表_1:
Value_ID Value_Code_1 Value_Code_2 Value_Code_3 1 465 325 129
表_2:
ID Text 465 this is a value 325 this value is a different one 129 hello world
我需要将表_1 中的代码替换为表_2 中的文本。我思考解决这个问题的方法似乎很长而且毛茸茸的,有没有更快、更好的方法来做到这一点?我必须对大约 40 列而不是我的示例中的 3 列执行此操作。
我的代码:
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
谢谢。
I have the following tables:
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
I need to replace the codes in Table_1 with the Text from Table_2. The way I thought about solving it seems quite long and hairy, is there a quicker, better way of doing this? I have to do this for around 40 columns and not 3 as in my example.
My code:
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
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以做得更简单,如下所示:
您仍然需要对所有 40 列执行此操作。
You can do it simpler, like this:
You still need to do it for all 40 columns.
我不知道这是否比 40 个连接的性能更高或更低,或者它是否更容易,但这是一个值得考虑的选项...
如果您要规范化您的 Table1,它会变得更加容易.. (
这与使用 UNPIVOT 的答案类似)
I don't know if this is more or less performant than 40 joins, or if it is easier or not, but it's an option to consider...
If you were to normalise your Table1, it becomes even easier...
(This is similar to the answer that uses UNPIVOT)