MySql 统计查询 本月 ,上月,上上个月销售统计以及 按天 按周 按月 按年进行统计

  一. 用于统计当月,上月,上上月的销售额统计。通过格式化销售日期进行查询。

SELECT IFNULL(SUM(p.settle_price),0) AS settlePrice,'本月' AS typeName 
    FROM package p 
WHERE  DATE_FORMAT( p.consume_time, '%Y%m' ) = DATE_FORMAT( CURDATE( ) , '%Y%m' )
UNION
SELECT IFNULL(SUM(p.settle_price),0) AS settlePrice,'上月' AS typeName 
    FROM  package p 
WHERE PERIOD_DIFF( DATE_FORMAT( NOW( ) , '%Y%m' ) , DATE_FORMAT( p.consume_time, '%Y%m' ) ) =1
UNION
SELECT IFNULL(SUM(p.settle_price),0) AS settlePrice,'上上月' AS typeName 
    FROM  package p 
WHERE PERIOD_DIFF( DATE_FORMAT( NOW( ) , '%Y%m' ) , DATE_FORMAT( p.consume_time, '%Y%m' ) ) =2

   二. 按照 日 周 月 年 的周期进行查询统计

<!-- 按日查询 -->  
SELECT
	 DATE_FORMAT(created_date,'%Y-%m-%d') as time,sum(money) money 
FROM shpping_order where shop_id = 1000  GROUP BY  time  
<!-- 按月查询 -->  
SELECT 
	DATE_FORMAT(created_date,'%Y-%m') as time,sum(money)  money 
FROM shpping_order where shop_id = 1000  GROUP BY  time  
<!-- 按年查询 -->  
SELECT 
	DATE_FORMAT(created_date,'%Y') as time,sum(money)  money 
FROM shpping_order where shop_id = 1000  GROUP BY  time   
<!-- 按周查询 -->  
SELECT 
	DATE_FORMAT(created_date,'%Y-%u') as time,sum(money)  money 
FROM shpping_order where shop_id = 1000  GROUP BY  time

你可能感兴趣的:(Mysql,mysql,数据库,sql)