您可以通过将匿名函数传递给group 方法来按部分字段分组。任何时候您想从 group 函数中获得一些特殊行为时,请考虑使用匿名函数(lambda 函数)。
在这种情况下,您可以使用 match 方法传递一个正则表达式,该表达式将匹配一个包含 4 位破折号和 2 位数字 (\\d{4}-\\d{2}) 的字符串。
查询的外观如下:
r.table('29969411')
.group(function (row) {
return row('date').match("\\d{4}-\\d{2}")
}).sum('cost')
在表格中给出以下条目:
{
"cost": 0.25 ,
"date": "2015-02-02" ,
"duration": 46 ,
"id": "1ff56fdd-9152-4729-baa4-c9736adbe54f" ,
"type": "outgoing"
}, {
"cost": 0.25 ,
"date": "2015-03-02" ,
"duration": 46 ,
"id": "74a453ec-531c-4fb0-a463-661b122d47df" ,
"type": "outgoing"
}, {
"cost": 0.25 ,
"date": "2015-01-02" ,
"duration": 46 ,
"id": "bfa9aa42-51c0-43ef-af3d-24de15ed6571" ,
"type": "outgoing"
}, {
"cost": 0.25 ,
"date": "2015-01-99" ,
"duration": 46 ,
"id": "c93ac248-f214-4649-a355-bfc814169456" ,
"type": "outgoing"
}
结果如下:
[
{
"group": {
"end": 7 ,
"groups": [ ],
"start": 0 ,
"str": "2015-01"
} ,
"reduction": 0.5
} ,
{
"group": {
"end": 7 ,
"groups": [ ],
"start": 0 ,
"str": "2015-02"
} ,
"reduction": 0.25
} ,
{
"group": {
"end": 7 ,
"groups": [ ],
"start": 0 ,
"str": "2015-03"
} ,
"reduction": 0.25
}
]