krishn Patel
krishn Patel

Reputation: 2599

Group by with Array in json with N1QL Couchbase

I have jsons like below

"Company|1000":{
  "_id": 1000,
  "_type": "Company",
  "transactions": [
    {
      "amount": 96.9,
      "date": "2016-10-11T18:30:00.000Z",
    },
    {
      "amount": 77.9,
      "date": "2016-9-01T18:30:00.000Z",
    }
  ],
}

I want to all transaction count group by month and year I am try to do below query but it out put is different.

    select ARRAY DATE_PART_MILLIS(STR_TO_MILLIS(x.date),'month')  FOR x IN 
Company.transactions END m, 
    ARRAY DATE_PART_MILLIS(STR_TO_MILLIS(z.date),'year') FOR z IN 
Company.transactions  END y,
    count(CASE WHEN array_count(b) > 0 THEN array_count(b) ELSE 0 END) 
Deposits
    from Inheritx Company 
    LET b = ARRAY TONUMBER(x.amount) FOR x in Company.transactions WHEN 
x.type IN [0] END
    where Company._type="Company"
    GROUP BY ARRAY DATE_PART_MILLIS(STR_TO_MILLIS(x.date),'month') FOR x IN 
Company.transactions END,
    ARRAY DATE_PART_MILLIS(STR_TO_MILLIS(x.date),'year') FOR x IN 
Company.transactions END

I want out put like

y       m    count 

2016     9     2
2016     10    12
2016     8     52

Upvotes: 2

Views: 696

Answers (1)

krishn Patel
krishn Patel

Reputation: 2599

I have done by below query

    SELECT DATE_PART_MILLIS(STR_TO_MILLIS(newTransaction.date),'month')  m, 
DATE_PART_MILLIS(STR_TO_MILLIS(newTransaction.date),'year')  y, 
count(CASE WHEN newTransaction.transactionType IN [0] THEN 1 ELSE NULL END) 
Deposits 
FROM Inheritx Users  
join Inheritx Company on keys('Company|'|| TOSTRING(Users.company)) 
UNNEST  Company.transactions  as newTransaction 
WHERE Users._type='User' and DATE_PART_MILLIS(STR_TO_MILLIS(newTransaction.date),'year')=2016
group by DATE_PART_MILLIS(STR_TO_MILLIS(newTransaction.date),'month') 
order by DATE_PART_MILLIS(STR_TO_MILLIS(newTransaction.date),'month')

Upvotes: 2

Related Questions