我有一份我想要的库存单位和销售交易清单,(1)按单位SKU加入,以及(2)按日期先进先出顺序将一笔交易与一个库存单位关联。我在第二部分遇到了麻烦。
我能想到的最好的是:
SELECT `units`.`unit_date`, `units`.`unit_id`, `trans`.`tran_date`, `trans`.`tran_id`, `units`.`unit_sku` FROM `units`
INNER JOIN `trans`
ON `trans`.`unit_sku` = `units`.`unit_sku`
GROUP BY `trans`.`tran_id`, `trans`.`unit_sku`
ORDER BY `units`.`unit_date` asc, `trans`.`tran_date` asc
;
units
表:
unit_date | unit_id | unit_sku
2015-06-01 | 1 | U1KLM
2015-06-02 | 2 | U1KLM
2015-06-03 | 3 | U2QRS
2015-06-04 | 4 | U2QRS
2015-06-05 | 5 | U1KLM
trans
表:
tran_date | tran_id | unit_sku
2015-06-11 | A | U2QRS
2015-06-12 | B | U1KLM
2015-06-13 | C | U1KLM
2015-06-14 | D | U2QRS
2015-06-15 | E | U1KLM
期望的结果是tran_id
一个unit_id
加入unit_sku
unit_date
的最早到最新订单unit_date | unit_id | tran_date | tran_id | unit_sku
2015-06-01 | 1 | 2015-06-12 | B | U1KLM
2015-06-02 | 2 | 2015-06-13 | C | U1KLM
2015-06-03 | 3 | 2015-06-11 | A | U2QRS
2015-06-04 | 4 | 2015-06-14 | D | U2QRS
2015-06-05 | 5 | 2015-06-15 | E | U1KLM
:
tran_id
查询(不受欢迎)结果仅将unit_id
加入unit_sku
最早出现的unit_date | unit_id | tran_date | tran_id | unit_sku
2015-06-01 | 1 | 2015-06-12 | B | U1KLM
2015-06-01 | 1 | 2015-06-13 | C | U1KLM
2015-06-01 | 1 | 2015-06-15 | E | U1KLM
2015-06-03 | 3 | 2015-06-11 | A | U2QRS
2015-06-03 | 3 | 2015-06-14 | D | U2QRS
:
unit_date
有关如何获得所需结果的任何想法?在此设置中,只有tran_date
和DROP TEMPORARY TABLE IF EXISTS `units`;
DROP TEMPORARY TABLE IF EXISTS `trans`;
CREATE TEMPORARY TABLE `units` (`unit_date` date, `unit_id` char(1) , `unit_sku` char(5), PRIMARY KEY(`unit_id`));
CREATE TEMPORARY TABLE `trans` (`tran_date` date, `tran_id` char(1) , `unit_sku` char(5), PRIMARY KEY(`tran_id`));
INSERT INTO `units` (`unit_date`, `unit_id`, `unit_sku`) VALUES
('2015-06-01', '1', 'U1KLM')
, ('2015-06-02', '2', 'U1KLM')
, ('2015-06-03', '3', 'U2QRS')
, ('2015-06-04', '4', 'U2QRS')
, ('2015-06-05', '5', 'U1KLM')
;
INSERT INTO `trans` (`tran_date`, `tran_id`, `unit_sku`) VALUES
('2015-06-11', 'A', 'U2QRS')
, ('2015-06-12', 'B', 'U1KLM')
, ('2015-06-13', 'C', 'U1KLM')
, ('2015-06-14', 'D', 'U2QRS')
, ('2015-06-15', 'E', 'U1KLM')
;
SELECT `units`.`unit_date`, `units`.`unit_id`, `trans`.`tran_date`, `trans`.`tran_id`, `units`.`unit_sku` FROM `units`
INNER JOIN `trans`
ON `trans`.`unit_sku` = `units`.`unit_sku`
GROUP BY `trans`.`tran_id`, `trans`.`unit_sku`
ORDER BY `units`.`unit_date` asc, `trans`.`tran_date` asc
;
可以排序;其余的是随机生成的。
Repro脚本:
to_representation()
答案 0 :(得分:2)
我相信这就是你要找的东西:(这是假设1比1的关系)
SET @UNITRN := 0;
SET @TRANSRN :=0;
SELECT A.`unit_date`, A.`unit_id`, B.`tran_date`, B.`tran_id`, A.`unit_sku` FROM (SELECT @UNITRN := @UNITRN + 1 AS ROWNUM, UNIT_DATE, UNIT_ID, UNIT_SKU FROM UNITS ORDER BY UNIT_SKU, UNIT_DATE ASC) A
JOIN (SELECT @TRANSRN := @TRANSRN + 1 AS ROWNUM, TRAN_DATE, TRAN_ID, UNIT_SKU FROM TRANS ORDER BY UNIT_SKU, TRAN_DATE ASC) B
ON A.UNIT_SKU = B.UNIT_SKU
AND A.ROWNUM = B.ROWNUM
ORDER BY A.UNIT_DATE ASC