I have 2 tables in SQL Server:
Table 1 : Department
DeptId Dept Name
------------------
1 Software Development
2 Testing
3 Customization
Table 2 : Designation
DesigId Desig Name DeptId
---------------------------
1 TL 1
2 PL 1
3 TestEngg 2
4 SE 3
I want the following output which takes department as column heading and group designation under the corresponding department column,
Software Development Testing Customization
TL TestEngg SE
PL
I tried with the below query but Im able to get only the Id’s
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)
Your code was so very close. My suggestion when working with
PIVOTespecially a dynamic version is to write the static version first, then convert it to dynamic sql.The static version, where you hard-code values is like this:
See SQL Fiddle with Demo. The static version allows you to be sure that the syntax is correct and all values, columns etc are in the right places.
Then once you have the syntax it is easy to convert to the dynamic SQL version:
See SQL Fiddle with Demo
Both give the result:
You will notice that I added the line
row_number() over(partition by s.deptid order by s.desigid) rnto theSELECTstatement. This allows you to return more than oneDesig Namefor eachDept Name, without this you will only return one value.