gpt4 book ai didi

javascript - CouchDB,如何在一个 View 中计算两个值

转载 作者:行者123 更新时间:2023-11-27 23:14:37 25 4
gpt4 key购买 nike

我有这样的文件:

{"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”作为总升的关键来调用 View ,那么我需要在减少以下内容后得到:

["A","2016"] {global: 50900, user: 19900}
["A","2015"] {global: 54032, user: 12030}

谢谢,

迭戈

最佳答案

嗯..这是我的想法:

  1. 您可以使用 POST 设置两个 Key。

    function(doc) {  var total={};  total={year:doc.year,litres:doc.litres};  emit(doc.user, {user:total,years:[total]});  emit("", {user:"",years:[total]});}

Query:

     curl -X POST  http://localhost:5984/test_a/_design/test/_view/test -H "Content-type:application/json" -d '{"keys":["A",""]}'    

Result (shortened):

 "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}]}}    
if you THEN make a reduce that collects the data from both keys:

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}
}
}
}

] }

我有点懒..所以请自行检查reduce/rereduce...

关于javascript - CouchDB,如何在一个 View 中计算两个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35922331/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com