我有'user'文档,其中包含名为'Orders'的数组。每个订单都有“标题”,“日期”,“费用”等属性。我想计算数据库中每个用户的每笔订单费用的总和。
这是地图功能:
map: function(doc) {
if (doc.Doc_type && doc.Doc_type === 'user' && doc.Orders) {
for (var i = 0; i < doc.Orders.length; i++) {
emit([doc.Orders[i].Order_date], doc.Orders[i].Fee);
}
}
}
还原功能:
reduce: function (keys, values, rereduce){
var sum = 0;
for(var i=0,fee;fee=values[i];i++){
sum+=fee;
}
return {
Transactions: sum,
Revenue: 10
};
}
我得到的结果是:
{"Transactions":"0[object Object][object Object]","Revenue":10}}
答案 0 :(得分:0)
为简单起见,我不使用您的特定数据结构,但名称应该是自我解释的。
发出键/值对:username /:fee(也许你必须将它解析为整数/浮点数),就像你在代码中所做的那样(地图):
CREATE PROCEDURE SelectYearly (@Year INT)
AS BEGIN
-- define two variables for the beginning of the current year, and the beginning of the next year
DECLARE @BeginningYear DATE
DECLARE @BeginningNextYear DATE
-- set the two variables - use the ISO-8601 format YYYYMMDD to be safe from any language/regional settings
SET @BeginningYear = CAST(CAST(@Year AS CHAR(4)) + '0101' AS DATE)
SET @BeginningNextYear = CAST(CAST(@Year+1 AS CHAR(4)) + '0101' AS DATE)
-- do whatever you need to do, and use the two variables to limit the selection
-- use the "YourDateCol >= @BeginningYear AND YourDateCol < @BeginningNextYear" syntax
-- to select all data for that given year that you're interested in
SELECT
(list of columns)
FROM
(your table IN question)
WHERE
YourDateCol >= @BeginningYear AND YourDateCol < @BeginningNextYear
END
索引中的每个用户名都会获得一个或多个订单行。如果您使用for(every_order) {
emit(username, fee)
}
请求视图,您将获得响应结果数组中的所有订单行。现在您可以总结客户端的费用,例如在浏览器中或 - 正如您所要求的那样 - 使用内置的reduce函数执行相同的服务器端
?key=":username"
每个用户名将获得一行,订单费用总额为值。