I am trying to develop a pivot table. Please see the attached image for required output. I am unable to design the pivot query for the required solution.
This is my sql query ::
select
b.SchoolName,
c.KaryakramName,
a.NikashaAmount
from TBL_NIKASHA a
inner join TBL_SCHOOL b on b.SchoolId = a.SchoolId
inner join TBL_KARYAKRAM c on a.KaryakramId = c.KaryakramId
WHERE
a.NikashaType = 1 and c.karyakramType = 1
order by a.SchoolId;
Here, NikashaType & karyakramType come from user.
I have to show the result of this query in pivot table. What I have done so far::
declare @columns nvarchar(max) = '', @sql nvarchar(max) = '';
select
@columns += QUOTENAME(c.KaryakramName) + ','
from TBL_NIKASHA a
inner join TBL_SCHOOL b on b.SchoolId = a.SchoolId
inner join TBL_KARYAKRAM c on a.KaryakramId = c.KaryakramId
WHERE
a.NikashaType = 1 and c.karyakramType = 1
SET @columns = left(@columns, len(@columns)-1);
set @sql = '
select * from
(
) t
pivot
(
a.NikashaAmount,
for c.KaryakramName in ('+ @columns+')
) as pivot_table
';
SELECT S.SchoolName
,MAX(CASE WHEN K.KaryakramName = 'sports materials' THEN N.NikashaAmount END) AS Sports_Materials
,MAX(CASE WHEN K.KaryakramName = 'salary management' THEN N.NikashaAmount END) AS Salary_Management
FROM TBL_NIKASHA N
INNER JOIN TBL_SCHOOL S
ON S.SchoolId = N.SchoolId
INNER JOIN TBL_KARYAKRAM K
ON N.KaryakramId = K.KaryakramId
WHERE N.NikashaType = 1
AND K.karyakramType = 1
GROUP BY S.SchoolName;