Question

I am getting Invalid column error on acctkey column. Can you please tell me what am I doing wrong?

select COUNT(acctkey) as Num, case
            when source_sys_cd in ('TRS','CLS') then source_sys_cd + '|'+[acct_num]                 
            when source_sys_cd = 'Hogan CIS' and [acct_type_cd] = 'DDA' then 'DDA' + '|'+ [acct_id]
            when source_sys_cd = 'Hogan CIS' and [acct_type_cd] != 'DDA' then 'TDA' +'|'+ [acct_id]
            when source_sys_cd = 'CLN' then source_sys_cd + '|'+ [acct_num]+ [acct_id]
            when source_sys_cd = 'RCC' then source_sys_cd + '|'+ [acct_id]
            when source_sys_cd = 'ITF' then source_sys_cd + '|'+ [acct_id]+ [acct_num]
            when source_sys_cd = 'SEC' then source_sys_cd + '|'+ [acct_id]
            else source_sys_cd + '|'+ [acct_num]
            end  as acctkey
            from mtb..STAGING_CUST_ACCT
            group by source_sys_cd
            ,acct_id
            ,acct_num
            ,acctkey
            ,acct_type_cd
Was it helpful?

Solution

In your case, you could technically fix the problem just by removing acctkey from the group by:

        group by source_sys_cd, acct_id, acct_num, acct_type_cd

All these columns are included in the definition of the acctkey (if I didn't miss anything). However, I doubt that is what you really want, because that is likely to produce duplicates for the acctkey.

Instead, I think you want:

with t as (
        select t.*,
           (case
            when source_sys_cd in ('TRS','CLS') then source_sys_cd + '|'+[acct_num]                 
            when source_sys_cd = 'Hogan CIS' and [acct_type_cd] = 'DDA' then 'DDA' + '|'+ [acct_id]
            when source_sys_cd = 'Hogan CIS' and [acct_type_cd] != 'DDA' then 'TDA' +'|'+ [acct_id]
            when source_sys_cd = 'CLN' then source_sys_cd + '|'+ [acct_num]+ [acct_id]
            when source_sys_cd = 'RCC' then source_sys_cd + '|'+ [acct_id]
            when source_sys_cd = 'ITF' then source_sys_cd + '|'+ [acct_id]+ [acct_num]
            when source_sys_cd = 'SEC' then source_sys_cd + '|'+ [acct_id]
            else source_sys_cd + '|'+ [acct_num]
            end)  as acctkey
        from mtb..STAGING_CUST_ACCT t
       )
select count(*), acctkey
from t
group by acctkey;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top