0

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!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
sai
  • 1
  • 4
  • 1
    [Bad habits to kick : using old-style JOINs](https://sqlblog.org/2009/10/08/bad-habits-to-kick-using-old-style-joins) - that old-style *comma-separated list of tables* style was replaced with the *proper* ANSI `JOIN` syntax in the ANSI-**92** SQL Standard (**25 years** ago) and its use is discouraged – marc_s Dec 03 '17 at 17:57

1 Answers1

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.

Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275
  • Thanks for your help.I am getting this result ReviewID Consultant List CD8EC961-84CF-4136-BAF3-0F0D4EF9C040 Pandurang CD8EC961-84CF-4136-BAF3-0F0D4EF9C040 Raja EC802729-402D-4F7D-B0BE-10F72C2CF88A DIVYA EC802729-402D-4F7D-B0BE-10F72C2CF88A KOPPU MD But I need to get like this ReviewID Consultant List CD8EC961-84CF-4136-BAF3-0F0D4EF9C040 Pandurang,Raja EC802729-402D-4F7D-B0BE-10F72C2CF88A DIVYA, KOPPU MD – sai Dec 03 '17 at 21:33