简体   繁体   中英

updating a column to include values derived from another

I have a situation using where I have a table (tbl1) and have added a column to this which is currently all null. I want to use an update statement to populate this column with the values of 3 other columns joined together. 1 of these other columns is fine as it is to be use, but the other two have values which require joining with another table (tbl2) to look up a single character associated code as per the table sample below from tbl2. CostType and RefType from tbl2 exist in tbl1, but I want to bring the CostCode and RefCode to the empty column of tbl1.I have also shown what i've tried using Advantage SQL Architect. Can't see to get it to work though.

update tbl1
set emptycolumn=tbl.column1+tbl2.costcode+tbl2.refcode
from tbl1 left join tbl2 on (tbl1.costtype=tbl2.costtype)
          left join tbl2 on (tbl1.reftype=tbl2.reftype)

CostCode    CostType          RefCode   RefType
A            Apportioned Cost   E      EmployeeID
J            Funding Adjustment I      Invoice
G            Grant              G      Grant Recipient
M            Grant Management   L      LearnRefNumber
O            Other Costs        N      CompanyName
E            Staff Expenses     O      Other
F            Staff Full Time    C      Authorised Claims
P            Staff Part Time    A      Audit Adjustment
U            Unit Cost      
D            Unit Cost Deduction        
S            Start Payment      
C            Completion Payment     

I believe your syntax is ok, so I'm guessing the value remains NULL . If so, you might just need coalesce() :

update tbl1
     set emptycolumn = (coalesce(tbl.column1, 0) + -- not sure if it starts as NULL
                        coalesce(tbl2.costcode, 0) +
                        coalesce(tbl2.refcode, 0)
                       )
from tbl1 left join
     tbl2
     on tbl1.costtype = tbl2.costtype left join
     tbl2
     on tbl1.reftype = tbl2.reftype;

If you intend string concatenation, then use '' rather than 0 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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