I have this query
WITH cte AS (SELECT CenterId, EOMONTH(MIN(Change_date)) AS EOM_Date, EOMONTH(MAX(Change_date)) AS finish
FROM #tempCenters
GROUP BY CenterId
UNION ALL
SELECT CenterId, EOMONTH(DATEADD(MONTH, 1, EOM_Date)), finish
FROM cte
WHERE EOM_Date < finish)
SELECT DISTINCT cte.CenterId,
FIRST_VALUE(Members) OVER(PARTITION BY cte.CenterId, cte.EOM_Date ORDER BY tc.Change_date DESC) AS 'EndOfMonthData.Members',
cte.EOM_Date AS 'EndOfMonthData.Date'
FROM cte
LEFT JOIN #tempCenters tc ON cte.CenterId = tc.CenterId AND cte.EOM_Date >= tc.Change_date
ORDER BY cte.CenterId, EOM_Date
FOR JSON PATH, ROOT('data')
which returns this
| CenterID | Members | EOM_Date |
|---|---|---|
| 1 | 100 | 2020-02-29 |
| 1 | 100 | 2020-03-31 |
| 1 | 130 | 2020-04-30 |
| 1 | 130 | 2020-05-31 |
| 1 | 130 | 2020-06-30 |
| 1 | 130 | 2020-07-31 |
| 1 | 130 | 2020-08-31 |
| 1 | 180 | 2020-09-30 |
| 2 | 200 | 2020-01-31 |
| 2 | 200 | 2020-02-29 |
| 2 | 106 | 2020-03-31 |
| 2 | 106 | 2020-04-30 |
| 2 | 106 | 2020-05-31 |
| 2 | 135 | 2020-06-30 |
but I need the result as JSON in the following format:
{
"data": [
{
"centerId": 1,
"EndOfMonthData": {
"2020-01-30": 100.00,
"2020-02-28": 100.00,
"2020-03-31": 130.00
...
}
},
{
"centerId": 2,
"EndOfMonthData": {
"2020-01-30": 200.00,
"2020-02-28": 200.00,
"2020-03-31": 106.00,
...
}
}
]
But this is the output I've got so far
{
"data": [
{
"CenterId": 1,
"EndOfMonthData": {
"Members": 100,
"Date": "2020-02-29"
}
},
{
"CenterId": 1,
"EndOfMonthData": {
"Members": 100,
"Date": "2020-03-31"
}
},
... ] }
I've tried with the JSON AUTO, JSON PATH with dots, without dots, but nothing close to what I need. Any help will be really appreciated.