假设一个表sx_product_wma表,它的结构如下:
CREATE TABLE `sx_product_wma` ( `id` int NOT NULL AUTO_INCREMENT, `product_id` int NOT NULL, `price` decimal(12, 2) NOT NULL, `wma_price` decimal(12, 2) NOT NULL, `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL, `inbound_date` datetime NOT NULL, `quantity` decimal(10, 2) NOT NULL, `inbound_kind` int NOT NULL DEFAULT 0, `left_quantity` decimal(10, 2) NOT NULL, `order_id` int NOT NULL DEFAULT 0, `item_id` int NOT NULL DEFAULT 0, PRIMARY KEY (`id`) USING BTREE, INDEX `index_product_wmas_on_product_id`(`product_id`) USING BTREE, INDEX `index_product_wmas_on_order_id`(`order_id`) USING BTREE, INDEX `index_product_wmas_on_item_id`(`item_id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 312438 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
这个表记录商品的加权平均价,inbound_kind: 1:入库,2:出库
假设我们获取一段时间内,每个商品的最新的入库记录,那么我们使用窗口函数,如下:
select * from ( select pw.id, pw.product_id, pw.inbound_date, pw.inbound_kind, ROW_NUMBER() OVER(PARTITION by product_id order by inbound_date desc) as num1 from sx_product_wma as pw where pw.inbound_kind in (1) and pw.product_id in (19, 21, 127) )as d where d.num1 = 1
若是要获取每个商品的出库和入库记录各一条,那么我们可以这么做:
select * from ( select pw.id, pw.product_id, pw.inbound_date, pw.inbound_kind, ROW_NUMBER() OVER(PARTITION by product_id, inbound_kind order by inbound_kind desc, inbound_date desc) as num1 from sx_product_wma as pw where pw.inbound_kind in (1, 2) and pw.product_id in (19, 21, 127) )as d where d.num1 = 1