GROUP_CONCAT in SQL Server error

扶醉桌前 提交于 2020-01-16 09:06:08

问题


Error:Column 'ReviewConsultants.ConsultantID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

Query:

select 
    R.ReviewID, 
    STUFF((select distinct ',' + FirstName 
           from Users 
           where UserID = RC.ConsultantID 
           FOR XML PATH ('')), 1, 1, '') AS consultantlist
from 
    [Reviews] R, [ReviewConsultants] RC 
where 
    R.ReviewID = RC.ReviewID  
group by 
    R.ReviewID;

One review can have one or more consultants.I am trying to get the consultants for each review in a column with comma separated.

Note: names of the consultants are present in users table.

When I am trying to run the above query I am getting above error.Any help is greatly appreciated!


回答1:


In your case you could use DISTINCT:

select DISTINCT R.ReviewID, STUFF((select distinct ','+FirstName 
                                   from Users 
                                   where UserID=RC.ConsultantID 
                                  FOR XML PATH ('')), 1, 1, '') 
                             AS consultantlist
from [Reviews] R
JOIN [ReviewConsultants] RC 
  ON R.ReviewID=RC.ReviewID;

Please avoid old join syntax.



来源:https://stackoverflow.com/questions/47620677/group-concat-in-sql-server-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!