1

I have two tables:

Departments --< Employees

Department table has data such as:

id, Name
1, Marketing
2, Sales

Employees table has data such as:

id, Name, DepartmentId, RatePerDay
1, Alex,1, 40
2, Bob,1, 30
3, Calvin,1, 40
4, Dal,1, 30

I want to get two data sets back as follows for each department:

DepartmentName, Employee1,Employee12,Employee13,Employee14
Marketing, Alex, Bob, Calvin, Dal

DepartmentName, RatePerDay1, RatePerDay2, RatePerDay3, RatePerDay4
Marketing, 40,30,40,30

I have to write a MS SQL 2008 Stored procedure which achieves this result?

Any help is appreciated

2
  • 1
    there are a lot of the same questions rows to columns tsql Commented Oct 27, 2011 at 13:18
  • possible duplicate of SQL Server PIVOT perhaps? Commented Oct 27, 2011 at 13:39

2 Answers 2

1

Ok, First take a look at this link, since you are gonna need dynamic SQL. Then you can try the following:

DECLARE @EmployeesId VARCHAR(MAX), @EmployeesIdAlias VARCHAR(MAX), @Query1 VARCHAR(MAX), @Query2 VARCHAR(MAX)
DECLARE @Rates VARCHAR(MAX), @RatesAlias VARCHAR(MAX)

SELECT  @EmployeesId = ISNULL(@EmployeesId + ',', '') + '[' + CAST(Id AS VARCHAR(10)) + ']',
        @EmployeesIdAlias = ISNULL(@EmployeesIdAlias + ',', '') + '[' + CAST(Id AS VARCHAR(10)) + '] AS [Employee ' + CAST(Id AS VARCHAR(10)) + ']',
        @RatesAlias = ISNULL(@RatesAlias + ',', '') + '[' + CAST(Id AS VARCHAR(10)) + '] AS [Rate ' + CAST(Id AS VARCHAR(10)) + ']'
FROM Employees


SET @Query1 = '
SELECT Department, '+@EmployeesIdAlias+'
FROM (  SELECT A.Id, A.Name, B.Name Department
        FROM Employees A
        INNER JOIN Department B
        ON A.DepartmentId = B.Id) Source
PIVOT(MIN(Name) FOR Id IN ('+@EmployeesId+')) AS PT'

EXEC(@Query1)

SET @Query2 = '
SELECT Department, '+@RatesAlias+'
FROM (  SELECT A.Id, A.RatePerDay, B.Name Department
        FROM Employees A
        INNER JOIN Department B
        ON A.DepartmentId = B.Id) Source
PIVOT(MIN(RatePerDay) FOR Id IN ('+@EmployeesId+')) AS PT'

EXEC(@Query2)
Sign up to request clarification or add additional context in comments.

Comments

1

Pivot may work for what your doing:

http://msdn.microsoft.com/en-us/library/ms177410.aspx http://archive.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=PIVOTData

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.