需求:一种商品每天价格在变化,根据每天销售额和每天的单价得到当天的销售数量,每天销售总额为:货款 - 退款(使用type字段标明:0---货款,1---退款)
问题:每天不一定有退款,就会导致销售总额的计算中会出现空值。
解决:使用ifnull函数来做处理。
表:
建表语句:
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for product
-- ----------------------------
DROP TABLE IF EXISTS `product`;
CREATE TABLE `product` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`pro_id` int(11) NOT NULL,
`pro_price` decimal(10,0) DEFAULT NULL,
`pro_amount` decimal(10,0) DEFAULT NULL,
`valid` int(11) NOT NULL DEFAULT '1',
`type` int(11) DEFAULT NULL,
`date` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of product
-- ----------------------------
INSERT INTO `product` VALUES ('1', '1001', '30', '9562', '1', '0', '2017-12-21 00:00:00');
INSERT INTO `product` VALUES ('2', '1001', '30', '324', '1', '1', '2017-12-21 00:00:00');
INSERT INTO `product` VALUES ('3', '1001', '33', '6954', '1', '0', '2017-12-22 00:00:00');
INSERT INTO `product` VALUES ('4', '1002', '24', '3654', '1', '0', '2017-12-22 00:00:00');
select
pd.pro_id as 商品编号,
pd.pro_price as 单价,
(ifnull(p1.pro_amount,0) - ifnull(p2.pro_amount,0)) as 销售总额,
((ifnull(p1.pro_amount,0) - ifnull(p2.pro_amount,0))) / pd.pro_price as 销售总量,
pd.date as 日期
from
(SELECT DISTINCT pro_id,date,pro_price from product) pd
LEFT JOIN (SELECT pro_id,pro_amount,date from product where type = 0) p1 ON p1.pro_id = pd.pro_id and p1.date = pd.date
LEFT JOIN (SELECT pro_id,pro_amount,date from product where type = 1) p2 ON p2.pro_id = pd.pro_id and p2.date = pd.date
where (ifnull(p1.pro_amount,0) - ifnull(p2.pro_amount,0)) > 0 and pd.pro_price is not null
ORDER BY pd .date desc,pd .pro_id DESC