我有这样的文件
{
bills: [
{
id: "1",
total: 20.0
},
{
id: "1",
total: 20.0
},
{
id: "2",
total: 10.0
}
]
}
我想基于id属性区分总值的DISTINCT SUM,但是找不到这种情况的指令。
对于示例案例,预期总数为30.0。
当“id”:“1”具有不同的值时,您选择哪一个
{
bills: [
{
id: "1",
total: 20.0
},
{
id: "1",
total: 30.0
},
{
id: "2",
total: 10.0
}
]
}
通过使用子查询表达式https://docs.couchbase.com/server/6.0/n1ql/n1ql-language-reference/subqueries.html,您可以使用数组的完整选择功能。
如果值不同,则以下查询使用MAX。这是每个文件总和
SELECT ARRAY_SUM((SELECT RAW MAX(b.total) FROM d.bills AS b GROUP BY b.id)) AS s
FROM default AS d
WHERE ......
使用ARRAY运算符选择要使用的数组元素。
https://docs.couchbase.com/server/6.0/n1ql/n1ql-language-reference/collectionops.html#array
然后使用ARRAY_DISTINCT()和ARRAY_SUM()来计算总数。
https://docs.couchbase.com/server/6.0/n1ql/n1ql-language-reference/arrayfun.html#fn-array-distinct https://docs.couchbase.com/server/6.0/n1ql/n1ql-language-reference/arrayfun.html#fn-array-sum