我有两张桌子:
部门 - <员工
部门表格包含以下数据:
id, Name
1, Marketing
2, Sales
员工表包含以下数据:
id, Name, DepartmentId, RatePerDay
1, Alex,1, 40
2, Bob,1, 30
3, Calvin,1, 40
4, Dal,1, 30
我想为每个部门提供以下两个数据集:
DepartmentName, Employee1,Employee12,Employee13,Employee14
Marketing, Alex, Bob, Calvin, Dal
DepartmentName, RatePerDay1, RatePerDay2, RatePerDay3, RatePerDay4
Marketing, 40,30,40,30
我必须编写一个MS SQL 2008存储过程来实现这个结果吗?
感谢任何帮助
答案 0 :(得分:1)
Pivot可能会为您的工作而努力:
http://msdn.microsoft.com/en-us/library/ms177410.aspx http://archive.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=PIVOTData
答案 1 :(得分:1)
好的,首先看一下this link,因为你需要动态SQL。然后你可以尝试以下方法:
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)