使用其他表中的值创建一个新列

时间:2017-01-19 22:04:46

标签: sql postgresql

我有一个表,我使用两个表中的union来创建。我试图在使用case语句创建的新表中插入一个新列。我的要求是,如果新表的地址与地址匹配,则插入1(如果与salesdataA匹配)或2(如果与salesdataB匹配)。新列的名称是Project_ID。我怎么能这样做?

create table allsalesdata as
(select * from salesdataA
union all
select * from salesdataB)
order by 1 

select * from allsalesdata

ID                   Address                          Project_ID (requested)
1                    111 Obama Drive                           1
1                    111 New York Street                       2
2                    222 Clinton Drive                         1
2                    222 Vermont Road                          2
3                    333 Obama Street                          1
3                    333 Florida Drive                         2
4                    444 McCain Road                           1
4                    444 Georgia Lane                          2

select * from salesdataA:

ID                   Address
1                    111 Obama Drive
2                    222 Clinton Drive
3                    333 Obama Street
4                    444 McCain Road

select * from salesdataB:

ID                   Address
1                   111 New York Street
2                   222 Vermont Road
3                   333 Florida Drive
4                   444 Georgia Lane


update allsalesdata
CASE when sd.Address = pcr.Address then 1
else 2
end as Project_ID
left join allsatesdata sd on salesdataA pcr

1 个答案:

答案 0 :(得分:1)

创建表时将其放入:

create table allsalesdata as
    select a.*, 1 as project_id
    from salesdataA
    union all
    select b.*, 2
    from salesdataB b
    order by 1 ;