使用group by时无效的列名称错误

时间:2014-05-01 15:38:17

标签: sql sql-server group-by

我在acctkey列上收到无效列错误。你能告诉我我做错了什么吗?

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

1 个答案:

答案 0 :(得分:1)

在您的情况下,您可以通过以下方式从组中删除acctkey来解决问题:

        group by source_sys_cd, acct_id, acct_num, acct_type_cd

所有这些列都包含在acctkey的定义中(如果我没有遗漏任何内容)。但是,我怀疑这是你真正想要的,因为这可能会产生acctkey的重复。

相反,我认为你想要:

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;