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


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

字段名类型说明备注
F1Varchar销售ID
F2Varchar销售日期日期格式:2014-02-14
F3Varchar销售金额

表中的数据如下

(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.月份
运行效果:



(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 金额
运行效果:

技术
下载桌面版
GitHub
Gitee
SourceForge
百度网盘(提取码:draw)
云服务器优惠
华为云优惠券
腾讯云优惠券
阿里云优惠券
Vultr优惠券
站点信息
问题反馈
邮箱:[email protected]
吐槽一下
QQ群:766591547
关注微信