SQL Server错误中的GROUP_CONCAT

时间:2017-12-03 16:44:04

标签: sql-server tsql sql-server-group-concat

  

错误:列'ReviewConsultants.ConsultantID'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

查询:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    public enum MoveDirection
    {
        Up,
        Down
    }

    static class Program
    {
        static void Main(string[] args)
        {
            List<string> MyList = new List<string>
            {
                "Value 1", "Value 2", "Value 3"
            };

            DisplayList(MyList);
            Console.WriteLine("----------------");
            Move(MyList, 1, MoveDirection.Down);
            DisplayList(MyList);
            Console.WriteLine("----------------");
            Move(MyList, 2, MoveDirection.Up);
            DisplayList(MyList);

            Console.ReadLine();
        }


        public static void Move(List<string> list, int iIndexToMove, MoveDirection direction)
        {

            if (direction == MoveDirection.Up && iIndexToMove > 0)
            {
                var old = list[iIndexToMove - 1];
                list[iIndexToMove - 1] = list[iIndexToMove];
                list[iIndexToMove] = old;
            }
            else if(direction == MoveDirection.Down && iIndexToMove < list.Count() - 1)
            {
                var old = list[iIndexToMove + 1];
                list[iIndexToMove + 1] = list[iIndexToMove];
                list[iIndexToMove] = old;
            }
        }

        public static void DisplayList(List<string> list)
        {
            foreach (var item in list)
            {
                Console.WriteLine(item);
            }
        }

    }
}

一个评论可以有一个或多个顾问。我正在尝试将逗号分隔的列中的每个评论的顾问。

注意:顾问的名字出现在用户表中。

当我尝试运行上述查询时,我收到了上述错误。非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

在您的情况下,您可以使用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;

请避免旧的连接语法。