逗号分隔列表作为SQL SELECT结果的一部分

时间:2011-09-15 20:20:26

标签: sql

我想返回一份员工列表,有关他们的各种信息以及一个列,其中列出了他们每个月在逗号分隔列表中分配给他们的前三个项目的列表。我有一个select语句成功返回小时数,但我不知道如何将它嵌入到select statemnet中。以下是select语句。我试图在SQL Server中执行此操作。

        DECLARE @Projects varchar(max)
    SELECT Top(3) @Projects = COALESCE(@Projects+', ' ,'') + ltrim(rtrim(Projects.Title))
                FROM         EmployeeProjectPlanning INNER JOIN
                  Projects ON EmployeeProjectPlanning.ProjectID = Projects.ProjectID
                WHERE     (EmployeeProjectPlanning.EmpID = 1) AND (EmployeeProjectPlanning.MonthID = 9) AND (EmployeeProjectPlanning.Year = 2011)
                ORDER BY EmployeeProjectPlanning.Hours DESC
    SELECT @Projects

1 个答案:

答案 0 :(得分:2)

假设您使用的是SQL 2005或更高版本,则可以使用FOR XML在一个字段中创建逗号分隔列表。只需将以下内容放在您需要项目列的SELECT语句中:

SUBSTRING(
    (SELECT TOP (3) ','+ltrim(rtrim(Projects.Title)) 
     FROM  EmployeeProjectPlanning AS emp
     INNER JOIN Projects as proj ON emp.ProjectID = proj.ProjectID
     WHERE (emp.EmpID = 1)
        AND (emp.MonthID = 9)
        AND (emp.Year = 2011)
     ORDER BY emp.Hours DESC
    FOR XML PATH('')
),2,8000) AS Projects