简体   繁体   English

更新具有多个联接的多列

[英]Updating Multiple Columns with multiple Joins

I'm receiving some data from an external source, where the actual values are replaced with ids. 我正在从外部来源接收一些数据,其中实际值已替换为id。

| Serial# | Sex | Married | Income |
------------------------------------
|    1    |  1  |    2    |   1    |
|    2    |  1  |    1    |   3    |
|    3    |  1  |    2    |   2    |

Now, I've a Dimension table with the values for each id: 现在,我有一个Dimension表,其中包含每个id的值:

| Tag     |        Value        | Id |
--------------------------------------
| Sex     |  M                  | 1  |
| Sex     |  F                  | 2  |
| Married |  Y                  | 1  |
| Married |  N                  | 1  |
| Income  |  Less than 100      | 1  |
| Income  |  Between 100 and 1K | 2  |
| Income  |  More than 1K       | 3  |

Now, I want all the ids of the three columns Sex, Married & Income in the First table to be replaced with the values from the First Table. 现在,我希望用第一张表中的值替换第一张表中“性,已婚和收入”三列的所有ID。

Also, if a unknown Id comes in, which is not present in the Dimension Table, we would love to update with 'UNKNOWN' 另外,如果有一个未知的ID(维度表中不存在),我们希望更新为“ UNKNOWN”

This is just an example. 这只是一个例子。 My data contains ~100 such columns. 我的数据包含约100个此类列。 What will be the cheapest and fastest way to achieve that? 实现这一目标的最便宜,最快的方法是什么? I don't want to write 100s of UPDATE statements. 我不想写100条UPDATE语句。

I don't see the need to update anything, you can join the two tables: 我认为不需要更新任何内容,您可以将两个表连接起来:

select i."Serial#", 
       sd."Value" as sex, 
       md."Value" as married,
       id."Value" as income
from the_intput_table i
  join dimension sd on sd.id = i."Sex" and sd."Tag" = 'Sex'
  join dimension md on md.id = i."Married" and md."Tag" = 'Married'
  join dimension id on id.id = i."Income" and id."Tag" = 'Income'

If you want to update the existing column ID's with its value then it can be achieved using below query: 如果要使用其值更新现有列ID,则可以使用以下查询来实现:

UPDATE
table1
SET
    table1.Sex = Table_B.col1,
    table1.Married = Table_B.col1,
    table1.Income = Table_B.col1,
FROM table1
     INNET JOIN Dimension  as d1 ON t1.Sex = d1.Id AND d1.Tag = 'Sex'
     INNET JOIN Dimension  as d2 ON t1.Married = d2.Id AND d2.Tag = 'Married'
     INNET JOIN Dimension  as d3 ON t1.Income = d3.Id AND d3.Tag = 'Income'

Making few changes to the above code, 对上述代码进行少量更改,

 select i.Serial#, 
    case when sd.Value is not null then sd.Value else 'UNKNOWN' end as sex, 
    case when md.Value is not null then md.Value else 'UNKNOWN' end as married,
    case when id.Value is not null then id.Value else 'UNKNOWN' end as income
    from the_intput_table i
     left outer join dimension sd on sd.id = i.Sex and sd.Tag = 'Sex'
     left outer join dimension md on md.id = i.Married and md.Tag = 'Married'
     left outer join dimension id on id.id = i.Income and id.Tag = 'Income'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM