I have paycode numbers and Names from table Paycodes and I have Amount in monthlyTransaction. as follows:
Paycodes
Code Name
1 Basic Salary
2 Variable Deduction Amount
3 Fixed/Var Insurance PayCode
MonthlyTransaction
Code Amount
1 3000
2 10000
1 130000
1 150000
3 120000
I want it to be like this using pivot
Basic Salary Variable Deduction Amount Fixed/Var Insurance PayCode
31000 10000 120000
I want to use pivot to sum the Amount of each Paycode and I used this:-
DECLARE @data AS NVARCHAR(MAX)
DECLARE @query AS NVARCHAR(MAX)
-- DECLARE @data TABLE
--(
-- PaycodeName NVARCHAR(max)
--)
--INSERT INTO @data
-- ( PaycodeName )
--select dbo.Paycode.PayCodeName FROM dbo.Paycode
select @data = Paycode.PayCodeName FROM Paycode
set @query = 'SELECT * FROM (
SELECT Paycode.Name , MonthlyTransaction.Amount
From MonthlyTransaction
LEFT JOIN dbo.Paycode ON Paycode.code = MonthlyTransaction.Paycode
) AS s
PIVOT
(
SUM(Amount)
FOR Paycode.Name IN ('+@data+')
) AS pvt '
EXECUTE Sp_executesql @query
When I print @data it retrieve the last paycode only ! Can anyone help ?