After requesting help from local db-masters with no result, I would like to ask this question here. The output required is this for example:
Shelter ClientID Year Month Fees Amount Result
Homes T0ZK9KZM 2020 7 600.00 49.00 551.00
Here is an online demo: https://www.db-fiddle.com/f/uZraahz6huHqUBp3qjuk9z/3
The first part of above result (Shelter - Fees) is a query based on formid 25.
The second part (Amount) is a query based on formid 23.
The third part (Result) is a calculation: Fees - Amount
.
The combining factor is the ClientID
.
How can I merge these pivot queries of RSform data together to generate data for my Plotalot graph?
SELECT
Shelter,
ClientID,
Year,
Month,
FORMAT(SUM(Total), 2) AS Fees
FROM (
SELECT
MAX(IF(FieldName = 'SHELTER', FieldValue, NULL)) AS Shelter,
SUM(IF(FieldName = 'Total', FieldValue, NULL)) AS Total,
Max(IF(FieldName = 'ClientID', FieldValue, NULL)) AS ClientID,
MAX(IF(FieldName = 'STARTDATE', YEAR(FieldValue), NULL)) AS Year,
MAX(IF(FieldName = 'STARTDATE', MONTH(FieldValue), NULL)) AS Month
FROM o2pe0_rsform_submission_values
WHERE FormId = 25
GROUP BY SubmissionId
Having MAX(IF(FieldName = 'ClientId', FieldValue, NULL)) = '%%P1=0%%'
) DerivedTable
GROUP BY Shelter, ClientId, Year, Month
ORDER BY Shelter, ClientId, Year, Month
SELECT
Shelter,
ClientID,
Year,
Month,
FORMAT(SUM(Amount), 2) AS Amount
FROM (
SELECT
MAX(IF(FieldName = 'SHELTER', FieldValue, NULL)) AS Shelter,
SUM(IF(FieldName = 'Amount', FieldValue, NULL)) AS Amount,
Max(IF(FieldName = 'ClientID', FieldValue, NULL)) AS ClientID,
MAX(IF(FieldName = 'Month_payment', YEAR(FieldValue), NULL)) AS Year,
MAX(IF(FieldName = 'Month_payment', MONTH(FieldValue), NULL)) AS Month
FROM o2pe0_rsform_submission_values
WHERE FormId = 23
GROUP BY SubmissionId
Having MAX(IF(FieldName = 'ClientId', FieldValue, NULL)) = '%%P1=0%%'
) DerivedTable
GROUP BY Shelter, ClientId, Year, Month
ORDER BY Shelter, ClientId, Year, Month