技术饭
mysql:统计表每个日期数量总和以及每个日期累计的总和
copylian
0 评论
32851 浏览
2017.03.10
mysql:统计表每个日期数量总和以及每个日期累计的总和,今天公司出了需求说要统计数据报表,按照日期来分组,统计每个日期的某个字段总和、数量以及每个日期之前累计的总和,本来sql基础就薄弱,问了好多朋友也都没有做出来,刚开始一点头绪都没有,后面经过一番努力与同事指导,算是整出来一个方案,效率还没测试过。
下面直接看例子吧!
#查询订单表:jdt_order_buy SELECT DATE_FORMAT(a.pay_time, '%Y-%m-%d') AS reportdate, COUNT(*) AS buy_number, SUM(a.total_amount) AS nowday_buy_total_amount, (SELECT SUM(b.total_amount) FROM jdt_order_buy b WHERE b.`status` > 7 AND b.pay_time < reportdate ) AS all_buy_total_amountFROM jdt_order_buy a WHERE a.`status` > 7 GROUP BY reportdate
查询结果:
那么问题来了,可以统计单独一张表的,那么我想把另外一张表也按照上面的方法统计一下,然后把两张合并改怎么做呢?本来的想法是两张表直接left join或者union all,但是后来发现都不行,后面同事给了一个思路:新建一张时间表jt_date,然后通过这个时间与其他的两个表的时间做left join关联,sql语句如下:
SELECT tdate.day AS '统计日期', tbuy.buy_number AS '当日购买总人数', tbuy.nowday_buy_total_amount AS '当日购买金额', tbuy.all_buy_total_amount AS '累计购买金额', transom.romson_number AS '当日赎回数量', transom.nowday_ransom_total_amount AS '当日赎回总额', transom.all_ransom_total_amount AS '累计赎回总额'FROM jdt_date tdate LEFT JOIN ( #查询订单表:jdt_order_buy SELECT DATE_FORMAT(a.pay_time, '%Y-%m-%d') AS reportdate, COUNT(*) AS buy_number, SUM(a.total_amount) AS nowday_buy_total_amount, (SELECT SUM(b.total_amount) FROM jdt_order_buy b WHERE b.`status` > 7 AND b.pay_time < reportdate ) AS all_buy_total_amount FROM jdt_order_buy a WHERE a.`status` > 7 GROUP BY reportdate) tbuy ON tdate.day = tbuy.reportdate LEFT JOIN ( #查询赎回表:jdt_order_ransom SELECT DATE_FORMAT(a.ransom_time, '%Y-%m-%d') AS reportdate, COUNT(*) AS romson_number, SUM(a.total_amount) AS nowday_ransom_total_amount, (SELECT SUM(b.total_amount) FROM jdt_order_ransom b WHERE b.`status` = 9 AND b.ransom_time < reportdate ) AS all_ransom_total_amount FROM jdt_order_ransom a WHERE a.`status` = 9 GROUP BY reportdate) transom ON tdate.day = transom.reportdate ORDER BY tdate.day DESC
关联后的结果:
仅供参考!
感谢你的支持,我会继续努力!
扫码打赏,感谢您的支持!
文明上网理性发言!