我在 SQL Server 中有 2 个表:
表一:部门
DeptId Dept Name
------------------
1 Software Development
2 Testing
3 Customization
表 2:名称
DesigId Desig Name DeptId
---------------------------
1 TL 1
2 PL 1
3 TestEngg 2
4 SE 3
我想要以下输出,它将部门作为列标题和相应部门列下的组指定,
Software Development Testing Customization
TL TestEngg SE
PL
我尝试使用以下查询,但我只能获得 ID
DECLARE @deptcols AS VARCHAR(MAX);
DECLARE @querystr AS VARCHAR(MAX);
select @deptcols = STUFF((SELECT distinct ',' + QUOTENAME(Dept_Id)
FROM Designation
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @querystr = 'SELECT ' + @deptcols + ' from
(
select Desig_Name, Dept_Id,Desig_Id
from Designation
) p
pivot
(
count(Desig_Id) FOR Dept_Id in (' + @deptcols + ')
) pv '
execute(@querystr)