couchbase N1QL 在子文档中分组

couchbase N1QL group-by in sub-document

给定以下数据模型:

{
 "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查询信用额度?即:

{
  {
   "customerId": "a",
   "total": "20
  },
  {
   "customerId": "b",
   "total": "10
  }
}

对每个文档聚合使用 SUBQUERY 表达式

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;