简体   繁体   中英

Why am I getting invalid column name error in group by?

I am trying to make this request. I added the group by because I had duplicates. I am getting the error:

Invalid column name for the columns in the group by.

I have read a lot of posts regarding this type of error but I am still stuck. Also I would like to know if I should use sum() . Help please.

INSERT INTO tabA
       ([load_number]
        ,[load_date]
        ,[no_command]
        ,[no_document]
        ,[id_transc]
        ,[division_cd]
        ,[activity_cd]
        ,[project_cd])
 
select 1 [load_number]
      ,getdate() [load_date]
      ,'' [no_command]
      ,'' [no_document]
      ,coalesce(c.id_numb,-1) [id_transc]
      ,coalesce(b.elem_cd,-1) [division_cd]
      ,coalesce(d.budget_cd,-1) [activity_cd]
      ,'' [project_cd]

from tabB b

   left join tabC c on c.credit = b.account
   left join tabD d on d.activity = SUBSTRING([b.name],CHARINDEX('-',[b.name])+1,LEN([b.name])) and d.transc = '1010'


    group by [load_number]
            ,[load_date]
            ,[no_command]
            ,[no_document]
            ,[id_transc]
            ,[division_cd]
            ,[activity_cd]
            ,[project_cd]

If you are concerned about duplicates, you can just use select distinct :

select distinct 1 [load_number],
       getdate() [load_date],
       '' [no_command],
       '' [no_document],
       coalesce(c.id_numb,-1) [id_transc],
       coalesce(b.elem_cd,-1) [division_cd],
       coalesce(d.budget_cd,-1) [activity_cd],
       '' [project_cd]
from tabB b left join
     tabC c
     on c.credit = b.account left join
     tabD d
     on d.activity = SUBSTRING([b.name],CHARINDEX('-',[b.name])+1,LEN([b.name])) and d.transc = '1010';

You can't use column aliases defined in the select in the group by in SQL Server.

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