Greetings experts,
I am using the following stored procedure to create PIVOT table.
In this stored proc, year (eventYear) is created dynamically from transactions table.
The results are stored in a table called MemberHistory.
So far, the query is generating results.
The only issue I am so far is that value of Amount is stored in eventYear in the format of yyyy.
For instance, we could have value of eventYear as following:
2016, 1017, 2018, 2019
and max amount for each year is stored in each of the years as:
2016 2017 2018 2019
390.00 219.00 590.00 120.00
For some reason, the value of Amount are not getting stored in the years.
They are showing of as NULL
Any ideas what I am doing wrong?
Thanks in advance for your assistance
Here is exact code I am using:
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
memberName,
eventYear,
envelopeNumber,
registrationFee,
balance,
' + @cols + ' INTO dbo.MemberHistory from
(
SELECT
m.memberName,
t.eventYear,
t.eventYear,
t.envelopeNumber,
t.registrationFee,
t.Balance,
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