I have a table that has columns that I want to insert into another table with certain conditions. The closest I could get was using this post.
This is how I want to do it:
if (cnt > 50, avg_account, else null) as avg_account
if (cnt > 50, avg_change, else null) as avg_change
As shown above, I want to insert some columns from Table1
into Table2
and especially avg_account
and avg_change
columns when cnt
column in Table1
is > 50
.
I tried the following, I am not getting my desired output using the following code,
SELECT
id, branch, account, total, change,
'avg_account' = CASE
WHEN cnt > 50 THEN avg_account -- How can I refer to avg_account values?
ELSE 'Null'
END,
'avg_change' = CASE
WHEN cnt > 50 THEN avg_change -- How can I refer to avg_change values?
ELSE 'Null'
END
INTO
Table2
FROM
Table1
PRINT ' ' + CONVERT(VARCHAR, @@ROWCOUNT) + ' rows updated'
Is my approach correct? Can I get values as indicated in the code snippet? OR should I use a where
clause or subquery?
Any help would be appreciated.