Greetings experts,
I am using this pivot query so that when the query renders, two things will happen.
1, Year will be generated dynamically. This works.
2, When the value of Amount will be assigned to Year.
For instance, the value of years will be as follows:
2016 2017 2018 2019
200.00 250.00 300.00 500.00
So far, the years are having values of NULL. Everything else has the correct values.
Any ideas what I am doing wrong?
Many thanks in advance.
ALTER PROCEDURE [dbo].[uspGetPivotedData]
AS
drop table MemberHistory;
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX);
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(FORMAT(m.date_registered,'yyyy'))
FROM Members m
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT
TransactionID,
Balance,
memberName,
phone,
EmailAddress,
Address,
eventYear,
Description,
registrationFee,
' + @cols + ' INTO dbo.MemberHistory from
(
SELECT
t.TransactionID,
t.Balance,
m.memberName,
m.EmailAddress,
m.Phone,
m.Address,
t.EventYear,
p.Description,
registrationFee,
m.date_registered,
t.Amount
from dbo.Transactions AS t INNER JOIN dbo.Members AS m ON t .MemberID = m.MemberID INNER JOIN
dbo.PaymentTypes AS p ON t .TypeID = p.PaymentTypeID
) x
pivot
(
MAX(Amount)
for date_registered in (' + @cols + ')
) p '
EXECUTE sp_executesql @query