0

I would like to return a list of Employees, various information about them and a column with the list of the top 3 projects they have hours assigned to them each month in a comma separated list. I have a select statement that returns the hours successfully, but I'm not sure how to embed it into a select statemnet. Below is the select statement. I am trying to do this in 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
2
  • 3
    Please, please, please tell us what SQL product you're using. MySQL and SQLite would do this with GROUP_CONCAT, in SQL Server you need to write a scalar stored procedure to do it. Sep 15, 2011 at 20:22
  • judging by the syntax, it's MS SQL. Also, I find it useful to make an aggregate CLR function for this purpose, to mimic MySQL's group_concat, if access rights permit it.
    – Alex
    Sep 15, 2011 at 20:25

1 Answer 1

3

Assuming you are using SQL 2005 or higher, you can use FOR XML to create the comma separated list in one field. Just put the following in your SELECT statement where you need the projects column:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.