来自子文档数组的Couchbase N1QL查询和

问题描述 投票:1回答:1

我的couchbase数据库中有以下文档模型

{
 type:"account"
 id : "123",
 transactions: [
   { 
      type : "credit",
      value : 100
   },
   { 
      type : "debit",
      value : 10
   }
 ]
}

我如何查询所有帐户ID及其所有积分的总和?

couchbase n1ql
1个回答
4
投票

使用AS ARRAY函数https://docs.couchbase.com/server/6.0/n1ql/n1ql-language-reference/arrayfun.html

SELECT d.id, 
   ARRAY_SUM(ARRAY v.`value` FOR v IN d.transactions WHEN v.type = "credit" END) AS s  
FROM default AS d
WHERE d.type = "account";

要么

使用子查询表达式https://docs.couchbase.com/server/6.0/n1ql/n1ql-language-reference/subqueries.html

 SELECT d.id, 
       (SELECT RAW SUM(d1.`value`) 
        FROM d.transactions AS d1
        WHERE d1.type = "credit")[0] AS s  
    FROM default AS d
    WHERE d.type = "account";
© www.soinside.com 2019 - 2024. All rights reserved.