子文档中的couchbase N1QL分组依据
鉴于以下数据模型:子文档中的couchbase N1QL分组依据,couchbase,n1ql,Couchbase,N1ql,鉴于以下数据模型: { "events": [ { "customerId": "a", "type": "credit" , "value": 10 }, { "customerId": "a", "type": "cre
{
"events": [
{
"customerId": "a",
"type": "credit" ,
"value": 10
},
{
"customerId": "a",
"type": "credit" ,
"value": 10
},
{
"customerId": "b",
"type": "credit" ,
"value": 5
},
{
"customerId": "b",
"type": "credit" ,
"value": 5
}
]
}
如何按customerId查询积分的总和?i、 e:
{
{
"customerId": "a",
"total": "20
},
{
"customerId": "b",
"total": "10
}
}
每个文档聚合使用子查询表达式
SELECT d.*,
(SELECT e.customerId, SUM(e.`value`) AS total
FROM d.events AS e
WHERE ......
GROUP BY e.customerId) AS events
FROM default AS d
WHERE ...........;
用于整个查询
SELECT e.customerId, SUM(e.`value`) AS total
FROM default AS d
UNNEST d.events AS e
WHERE ......
GROUP BY e.customerId;
我假设你有不止一个这样的文档。您是希望在每个文档中聚合,还是希望在所有文档中聚合?@MatthewGroves是的,有多个此类文档,在文档级别聚合就可以了。vsr的答案是有效的。