答:
注意:我给的答案也不是最终的答案,因为我值计算了入库数据,但是在出库时没有将其算入,所以有点小问题,但是希望对你有帮助。
sql:
select d.* from
(
select c.transTypeName, c.ainvid, c.aamout, c.aprice, c.aqty, c.abilldate, (sum(c.bamount)+ c.aamout)/(sum(c.bqty)+ c.aqty) as avgValue from
(
select a.transTypeName as transTypeName , a.amount as aamout, a.invid as ainvid,
a.price as aprice, a.qty as aqty, a.billdate as abilldate,
b.amount as bamount, b.price as bprice, b.qty as bqty, b.billdate as bbilldate
from test1 a, test1 b where a.transTypeName='入库' and b.transTypeName ='入库' and a.invid = b.invid and a.billdate > b.billdate
) c group by c.aamout
union all
select transTypeName,amount,invid,price,qty, min(billdate), price as avgValue from test1 where transTypeName = '入库' GROUP BY invid
) d
order by d.abilldate
用到的 表结构和测试数据:
CREATE TABLE `test1` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`transTypeName` varchar(255) DEFAULT NULL,
`amount` varchar(255) DEFAULT NULL,
`invid` int(11) DEFAULT NULL,
`price` decimal(10,0) DEFAULT NULL,
`qty` int(11) DEFAULT NULL,
`billdate` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of test1
-- ----------------------------
INSERT INTO `test1` VALUES ('1', '入库', '828', '5', '207', '4', '2019-07-07 00:00:00');
INSERT INTO `test1` VALUES ('2', '入库', '200', '8', '10', '20', '2019-07-08 00:00:00');
INSERT INTO `test1` VALUES ('3', '入库', '2020', '5', '202', '10', '2019-07-09 00:00:00');
INSERT INTO `test1` VALUES ('4', '出库', '660', '5', '220', '3', '2019-07-10 00:00:00');
INSERT INTO `test1` VALUES ('5', '入库', '400', '5', '200', '2', '2019-07-11 00:00:00');
INSERT INTO `test1` VALUES ('6', '出库', '100', '5', '20', '5', '2019-07-12 00:00:00');
INSERT INTO `test1` VALUES ('7', '入库', '600', '5', '10', '60', '2019-07-20 00:00:00');