What's the best way to populate column A
with name
in df1
based on the common column ID
of df1
and df2
?
df1
ID A
122 nan
233 nan
...
df2
ID B name
122 10 real_name1
233 20 real_name2
...
to get:
ID A
122 real_name1
233 real_name2
...
Edit:
I would also like to change the column name A
to new_column_name
so the expected output looks like this:
ID new_column_name
122 real_name1
233 real_name2
...
Update:
Tried:
UPDATE t1
SET A = t2.name
FROM df1 t1
INNER JOIN df2 t2
ON t2.ID = t1.ID;
and it caught error:
Msg 8152, Level 16, State 2, Line 48
String or binary data would be truncated.
The statement has been terminated.
Update2:
Table definitions
df1
:
CREATE TABLE [dbo].[df1](
[ID] [nvarchar](20) NULL,
[SUB_ID2] [nvarchar](15) NOT NULL,
[DATE] [datetime2](7) NULL,
[MONTH] [nvarchar](4000) NULL,
[QTY] [numeric](20, 8) NOT NULL,
[SUB_ID] [nvarchar](15) NOT NULL,
[X] [nvarchar](20) NULL,
[SUBURB_ID] [nvarchar](30) NULL,
[PROJECT_NAME] [nvarchar](160) NULL,
[A] [varchar](10) NOT NULL
) ON [PRIMARY]
df2
:
CREATE TABLE [dbo].[df2](
[ID] [nvarchar](46) NULL,
[NAME1] [nvarchar](50) NULL,
[IDx] [nvarchar](15) NULL,
[P] [nvarchar](50) NULL,
[Q] [nvarchar](50) NULL,
[Z] [nvarchar](50) NULL,
[Y] [nvarchar](30) NULL,
[MARK] [nvarchar](10) NULL,
) ON [PRIMARY]
question from:
https://stackoverflow.com/questions/65930360/populate-column-based-on-another-column-in-sql 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…