I have a interesting challenge which i hope i can solve with N1QL vs having to do multiple query’s and than use API to build correct data. I have 2 type of docs, one lets called parent is the tract info and the second is the child which is farm. What i like to do is get a summary based on a status of the child for the parent.
Here is the query that gets me the info but not in desired format,
select c.name,
(SELECT Record.ownerOccupied,
COUNT(*) AS count
FROM Contacts
WHERE _type = 'farm'
AND Record.tract IN c.tract_id
GROUP BY Record.ownerOccupied
UNION ALL
SELECT COUNT(*) AS Total
FROM Contacts e
WHERE _type = 'farm'
AND e.Record.tract IN c.tract_id) as test
from Contacts c where _type = 'tract_info'
The above produces the following output
[
{
"name": "Brisa del Mar",
"test": [
{
"Total": 83
},
{
"count": 70,
"ownerOccupied": true
},
{
"count": 13,
"ownerOccupied": false
}
]
}
]
but i am looking to create output like this, is that possible ?
[
{
"name": "Brisa del Mar",
"Total": 83,
"ownerOccupied": 70,
"NoneOwnerOccupied": 13
}
]
i was able to create a desired Output with below query but not certain there is no belter way
SELECT c.name,
(
SELECT RAW
COUNT(*) AS ownerOccupied
FROM Contacts
WHERE _type = 'farm'
AND Record.tract IN c.tract_id and Record.ownerOccupied = true
GROUP BY Record.ownerOccupied)[0] as OwnerOccupied,
(
SELECT RAW
COUNT(*) AS NoneOwnerOccupied
FROM Contacts
WHERE _type = 'farm'
AND Record.tract IN c.tract_id and Record.ownerOccupied = false
GROUP BY Record.ownerOccupied)[0] as NoneOwnerOccupied,
(
SELECT RAW
COUNT(*) AS TotalCount
FROM Contacts
WHERE _type = 'farm'
AND Record.tract IN c.tract_id)[0] as TotalCount
FROM Contacts c
WHERE _type = 'tract_info'