2

I have document like this

    {
        bills: [
             { 
                  id: "1",
                  total: 20.0
              },
              { 
                  id: "1",
                  total: 20.0
              },
              { 
                  id: "2",
                  total: 10.0
              }
         ]
    }

I would like to do the DISTINCT SUM of total value with distinction based on id property but could not find and instruction for this case.

For the example case, the expected total is 30.0.

2 Answers 2

2

Use the ARRAY operator to select which elements of the array you want to use.

https://docs.couchbase.com/server/6.0/n1ql/n1ql-language-reference/collectionops.html#array

Then use ARRAY_DISTINCT() and ARRAY_SUM() to compute the total.

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

Sign up to request clarification or add additional context in comments.

4 Comments

The point is to select which elements to use, the elements are pretty much the same on the selection criteria. The ARRAY_DISTINCT works on basic data type and not object.
ARRAY_DISTINCT() works on any data type, In case of OBJECT if single character is different in field or value it is different. In case of ARRAY position also matters. If these functions doesn't solve use subquery expression as SELECT you can use any feature in the query
@vsr let me try the ARRAY_DISTINCT (again) on the object because it looks like better solution
the ARRAY_DISTINCT works with object (my previous try failed because I gave different total value), but the document on Couchbase site should be giving more example on this case ...
1

Which one you choose when “id”:“1” has different values

{
     bills: [
          { 
               id: "1",
              total: 20.0
          },
          { 
               id: "1",
              total: 30.0
          },
          { 
               id: "2",
              total: 10.0
          }
    ]
}

By using subquery expression https://docs.couchbase.com/server/6.0/n1ql/n1ql-language-reference/subqueries.html you can use complete select functionality of arrays.

In case of different values the following query uses MAX. This is per document sum

SELECT  ARRAY_SUM((SELECT RAW MAX(b.total) FROM d.bills AS b GROUP BY b.id)) AS s
FROM default AS d
WHERE ......

1 Comment

This is brilliant and looks like an answer to me! I will try and let you know! To your answer the total values are the same (there are other properties which are not the same)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.