使用多个联接更新多个列

时间:2018-01-09 07:45:10

标签: sql sql-update vertica

我从外部来源收到一些数据,其中实际值被替换为ID。

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

现在,我有一个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  |

现在,我想要三列“性别”,“已婚”和“已婚”中的所有ID。第一个表中的收入将替换为第一个表中的值。

此外,如果未知ID出现在维度表中,我们很乐意更新“未知”'

这只是一个例子。我的数据包含约100个这样的列。 实现这一目标的最便宜,最快捷的方法是什么? 我不想写100多份UPDATE语句。

3 个答案:

答案 0 :(得分:1)

我没有看到需要更新任何内容,你可以加入这两个表:

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'

答案 1 :(得分:0)

如果您想使用其值更新现有列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'

答案 2 :(得分:0)

对上述代码进行少量更改,

 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'