Mongodb aggregate 统计SQL(金额分类、分时统计、left join)

微信订单统计SQL
本文提供了一组用于微信订单统计的SQL查询案例,包括订单总体统计、按状态分类统计、按金额分类统计及按小时分布统计等。通过这些SQL查询,可以有效分析微信订单的数据特征。

记录一下用到的微信订单统计SQL:

- 订单统计:

db.orders.aggregate(
  { $match:{createDay:20180611} },
  { $group:{_id:null, recordCount:{$sum:1}, amount:{$sum:"$totalAmount"}, avgValue:{$avg:"$totalAmount"}} }
);

结果示例:
这里写图片描述

- 订单状态分类统计:

db.orders.aggregate(
  { $match:{createDay:20180611} },
  { $group:{_id:"$status", recordCount:{$sum:1}, amount:{$sum:"$totalAmount"}, avgValue:{$avg:"$totalAmount"}} }
);

结果示例:
这里写图片描述

- 订单金额分类统计:

db.orders.aggregate(
  { $match:{createDay:20180611} },
  { $group:{_id:"$totalAmount", recordCount:{$sum:1}, amount:{$sum:"$totalAmount"}, avgValue:{$avg:"$totalAmount"} } }
);

结果示例:
这里写图片描述

- 订单分时统计:

db.orders.aggregate(
  { $match:{day:20180611} },
  { $group:{_id:{ year: { $year: "$gmtCreate" }, month: { $month: "$gmtCreate" }, day: { $dayOfMonth: "$gmtCreate" }, hour: { $hour: "$gmtCreate" }  }, recordCount:{$sum:1}, amount:{$sum:"$totalAmount"} } },
  { $sort:{_id:1}}
).forEach(function(t){print(t._id.year+'-'+t._id.month+'-'+t._id.day+' '+t._id.hour+':00\t'+t.recordCount+'\t'+t.amount)});

结果示例(注意:这里要加8小时):
这里写图片描述

- 左连接查询:

--insert hour list:
db.hour.insert({hour:"1:00"});
db.hour.insert({hour:"2:00"});
db.hour.insert({hour:"3:00"});
db.hour.insert({hour:"4:00"});
db.hour.insert({hour:"5:00"});
--insert work log:
db.work_log.insert({name:'yown', hour:'3:00'});

db.hour.aggregate(
    {
      $lookup:
        {
          from: "work_log",
          localField: "hour",
          foreignField: "hour",
          as: "log_docs"
        }
   }
).forEach(function(t){
  print(t.hour+'\t' + (t.log_docs[0] == null ? '' : t.log_docs[0].name) + '\t' + (t.log_docs[0] == null ? '' : t.log_docs[0].hour));
});

结果示例:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值