MySQL统计每个月的销售合计数据

MySQL统计每个月的销售合计数据


在名为‘temp’数据库中有一张销售表(bb_sale),结构如下

字段名 类型 说明 备注
F1 Varchar 销售ID
F2 Varchar 销售日期 日期格式:2014-02-14
F3 Varchar 销售金额


表中的数据如下
MySQL统计每个月的销售合计数据_第1张图片
(1)统计2014年1至12月份,每个月的销售合计数据,格式如下:月份、金额

SELECT b.月份,COALESCE(SUM(a.F3),0) AS 金额
FROM bb_sale a RIGHT JOIN
(
  SELECT '2014-01' AS 月份 FROM dual
  union
  SELECT '2014-02' AS 月份 FROM dual
   union
  SELECT '2014-03' AS 月份 FROM dual
   union
  SELECT '2014-04' AS 月份 FROM dual
   union
  SELECT '2014-05' AS 月份 FROM dual
   union
  SELECT '2014-06' AS 月份 FROM dual
   union
  SELECT '2014-07' AS 月份 FROM dual
   union
  SELECT '2014-08' AS 月份 FROM dual
   union
  SELECT '2014-09' AS 月份 FROM dual
   union
  SELECT '2014-10' AS 月份 FROM dual
   union
  SELECT '2014-11' AS 月份 FROM dual
   union
  SELECT '2014-12' AS 月份 FROM dual
) b
ON LEFT(a.F2,7)=b.月份
GROUP BY b.月份

运行效果:
MySQL统计每个月的销售合计数据_第2张图片

(2)统计2014年1月份至12月份的销售合计数据,格式如下:月份、金额。这里的月份有点区别,比如1月份的数据,是指1月15号至2月15号之间的数据,同理2月份的数据,是指2月15号至3月15号之间的数据,以此类推。

SELECT '2014-01' AS 月份,COALESCE((SELECT SUM(F3) FROM bb_sale WHERE F2>='2014-01-15' AND F2 <'2014-02-15'),0) AS 金额
UNION
SELECT '2014-02' AS 月份,COALESCE((SELECT SUM(F3) FROM bb_sale WHERE F2>='2014-02-15' AND F2 <'2014-03-15'),0) AS 金额
UNION
SELECT '2014-03' AS 月份,COALESCE((SELECT SUM(F3) FROM bb_sale WHERE F2>='2014-03-15' AND F2 <'2014-04-15'),0) AS 金额
UNION
SELECT '2014-04' AS 月份,COALESCE((SELECT SUM(F3) FROM bb_sale WHERE F2>='2014-04-15' AND F2 <'2014-05-15'),0) AS 金额
UNION
SELECT '2014-05' AS 月份,COALESCE((SELECT SUM(F3) FROM bb_sale WHERE F2>='2014-05-15' AND F2 <'2014-06-15'),0) AS 金额
UNION
SELECT '2014-06' AS 月份,COALESCE((SELECT SUM(F3) FROM bb_sale WHERE F2>='2014-06-15' AND F2 <'2014-07-15'),0) AS 金额
UNION
SELECT '2014-07' AS 月份,COALESCE((SELECT SUM(F3) FROM bb_sale WHERE F2>='2014-07-15' AND F2 <'2014-08-15'),0) AS 金额
UNION
SELECT '2014-08' AS 月份,COALESCE((SELECT SUM(F3) FROM bb_sale WHERE F2>='2014-08-15' AND F2 <'2014-09-15'),0) AS 金额
UNION
SELECT '2014-09' AS 月份,COALESCE((SELECT SUM(F3) FROM bb_sale WHERE F2>='2014-09-15' AND F2 <'2014-09-15'),0) AS 金额
UNION
SELECT '2014-10' AS 月份,COALESCE((SELECT SUM(F3) FROM bb_sale WHERE F2>='2014-10-15' AND F2 <'2014-11-15'),0) AS 金额
UNION
SELECT '2014-11' AS 月份,COALESCE((SELECT SUM(F3) FROM bb_sale WHERE F2>='2014-11-15' AND F2 <'2014-12-15'),0) AS 金额
UNION
SELECT '2014-12' AS 月份,COALESCE((SELECT SUM(F3) FROM bb_sale WHERE F2>='2014-12-15' AND F2 <='2014-12-31' or F2>='2014-01-01' AND F2<'2014-01-15'),0) AS 金额

运行效果:
MySQL统计每个月的销售合计数据_第3张图片

你可能感兴趣的:(mysql)