Hi!
Below script not working.
Msg 8117, Level 16, State 1, Line 1
Operand data type char is invalid for sum operator.
CREATE TABLE #Students(Id int, Name nchar(20))
INSERT INTO #Students (Id, Name) VALUES (1, N'Rustam')
INSERT INTO #Students (Id, Name) VALUES (2, N'Muhammad')
INSERT INTO #Students (Id, Name) VALUES (3, N'Amirjon')
INSERT INTO #Students (Id, Name) VALUES (4, N'Sadriddin')
select * from #Students
--drop table #Students
CREATE TABLE #Cash(Id int, IdStd int, Course int, Fees money, LearnYear char(7))
INSERT INTO #Cash (Id, [IdStd], Course, Fees, LearnYear) VALUES (1, 1, 1, '3500', '2019/20')
INSERT INTO #Cash (Id, [IdStd], Course, Fees, LearnYear) VALUES (2, 2, 1, '3000', '2020/21')
INSERT INTO #Cash (Id, [IdStd], Course, Fees, LearnYear) VALUES (3, 3, 1, '3900', '2019/20')
INSERT INTO #Cash (Id, [IdStd], Course, Fees, LearnYear) VALUES (4, 4, 1, '4500', '2018/19')
INSERT INTO #Cash (Id, [IdStd], Course, Fees, LearnYear) VALUES (5, 5, 2, '3500', '2020/21')
INSERT INTO #Cash (Id, [IdStd], Course, Fees, LearnYear) VALUES (6, 6, 2, '3900', '2020/21')
INSERT INTO #Cash (Id, [IdStd], Course, Fees, LearnYear) VALUES (7, 7, 2, '4500', '2019/20')
INSERT INTO #Cash (Id, [IdStd], Course, Fees, LearnYear) VALUES (8, 8, 3, '4500', '2020/21')
select * from #Cash
--drop table #Cash
DECLARE @cols AS NVARCHAR(MAX),@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(convert(char(5), IdStd)+'_'+col)
from #Students s inner join #Cash a on s.Id = a.IdStd
cross apply
(
select 'LearnYear', 1
) c (col, so)
group by col, so, IdStd
order by IdStd, so
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT Name,' + @cols + '
from
(
select Name,
col = convert(char(5), IdStd)+''_''+col,
value
from #Students s inner join #Cash a on s.Id = a.IdStd
cross apply
(
select ''LearnYear'', LearnYear
) c (col, value)
) x
pivot
(
SUM(value)
for col in (' + @cols + ')
) p '
execute sp_executesql @query;