使用带有N1QL Couchbase的json中的Array进行分组

时间:2016-12-15 13:58:29

标签: couchbase n1ql

我有像下面的jsons

"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",
    }
  ],
}

我希望所有交易计数按月和年分组 我试着在下面查询,但它的输出是不同的。

    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

我想要像

一样
y       m    count 

2016     9     2
2016     10    12
2016     8     52

1 个答案:

答案 0 :(得分:2)

我已通过以下查询

完成
    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')