我有这样的文件:
{"user": "A","year": "2016","price": 3,"litres": 19900}
{"user": "B","year": "2016","price": 2.3,"litres": 16000}
{"user": "C","year": "2016","price": 2.9,"litres": 15000}
{"user": "A","year": "2015","price": 4,"litres": 12030}
{"user": "B","year": "2015","price": 3,"litres": 20002}
{"user": "C","year": "2015","price": 2.9,"litres": 22000}
我需要按年计算所有值的总和以及其中一个用户的总和,目标是将全局平均值与一个用户进行比较。
例如,如果我使用" A"作为总和的关键,我需要在减少类似的东西之后得到:
["A","2016"] {global: 50900, user: 19900}
["A","2015"] {global: 54032, user: 12030}
谢谢,
迭
答案 0 :(得分:1)
您无法通过一次通话完成此操作。如果您交换了您的密钥订单,那么该年份是第一个,那么用户,您可以对具有不同组级别的同一视图进行两次调用。组级别1将为您提供全局年度总计,组级别2将按用户总计给您年份。
答案 1 :(得分:0)
您可以使用POST设置两个密钥。
function(doc) { var total={}; total={year:doc.year,litres:doc.litres}; emit(doc.user, {user:total,years:[total]}); emit("", {user:"",years:[total]}); }
查询:
curl -X POST http://localhost:5984/test_a/_design/test/_view/test -H "Content-type:application/json" -d '{"keys":["A",""]}'
结果(缩短):
"key":"A","value":{"user":{"year":"2016","litres":19900},"years": [{"year":"2016","litres":19900}]}}, "key":"A","value":{"user":{"year":"2015","litres":12030},"years":[{"year":"2015","litres":12030}]}}, "key":"","value":{"user":"","years":[{"year":"2016","litres":19900}]}}, "key":"","value":{"user":"","years":[{"year":"2016","litres":16000}]}}, "key":"","value":{"user":"","years":[{"year":"2016","litres":15000}]}}, "key":"","value":{"user":"","years":[{"year":"2015","litres":12030}]}}, "key":"","value":{"user":"","years":[{"year":"2015","litres":20002}]}}, "key":"","value":{"user":"","years":[{"year":"2015","litres":22000}]}}如果你那么做一个从两个键收集数据的reduce:
function(keys, values, rereduce) {
var user_sum=0;
var total_a=[];
var v_values={};
var curUser="";
for (var i=0;i<keys.length;i++) {
if (keys[i]!="") {
curUser=keys[i][0];
}
values[i].years.forEach(function(year) {
if (v_values["year_"+year.year]) {
v_values["year_"+year.year]=
{year:year.year,
litres:v_values["year_"+year.year].litres+year.litres
};
}else{
v_values["year_"+year.year]={year:year.year,litres:year.litres};
}
});
}
return ({user:curUser,years:v_values})
}
你得到了
{"rows":[
{"key":"A","value":
{"user":"A",
"years":{
"year_2015": {"year":"2015","litres":12030},
"year_2016":{"year":"2016","litres":19900}
}
}
},
{"key":"","value":
{"user":"",
"years":{
"year_2015":{"year":"2015","litres":54032},
"year_2016":{"year":"2016","litres":50900}
}
}
}
] }
我有点懒..所以检查你自己的减少/减少...