当我使用窗口函数 ROW_NUMBER(( 添加列时,我看到顺序发生了变化。
结果是运行总计不正确。 (@ONorderQTYrunner(
谁能解释为什么 ROW_NUMBER(( 会更改排序顺序并导致运行总计错误?
下面的查询(使用 ROW_NUMBER(((返回第 1 行和第 2 行的意外 RUNNINGtotal 值:
1 57 A-123 69 4000 2020-06-10 4500
2 32 A-123 67 500 2020-07-01 500
3 59 A-123 69 2000 2020-07-15 6500
4 60 A-123 69 2000 2020-08-15 8500
如果没有 ROW_NUMBER(( 返回这个,正如我所期望的那样:
57 A-123 69 4000 2020-06-10 4000
32 A-123 67 500 2020-07-01 4500
59 A-123 69 2000 2020-07-15 6500
60 A-123 69 2000 2020-08-15 8500
CREATE TABLE IF NOT EXISTS `PURCHASEorders` (
`UniKey` int(11) NOT NULL AUTO_INCREMENT,
`PARTnumber` varchar(255) DEFAULT NULL,
`POnumber` varchar(255) NOT NULL,
`QTY` double DEFAULT 0,
`DOCKdate` date DEFAULT NULL,
PRIMARY KEY (`UniKey`),
KEY `PartNumber` (`PARTnumber`),
KEY `POnumber` (`POnumber`)
) DEFAULT CHARSET=utf8;
INSERT INTO `PURCHASEorders` (`UniKey`, `PARTnumber`,`POnumber`, `QTY`, `DOCKdate`) VALUES
('32', 'A-123', 67, 500, '2020-07-01 12:00:00'),
('57', 'A-123', 69, 4000,'2020-06-10 12:00:00'),
('59', 'A-123', 69, 2000,'2020-07-15 12:00:00'),
('60', 'A-123', 69, 2000,'2020-08-15 12:00:00');
SET @PARTnumber = 'A-123';
SET @ONorderQTYrunner =0;
SELECT DISTINCT
ROW_NUMBER() OVER(ORDER BY DOCKdate ASC) AS ONorderROWindex,
PO.UniKey,
PO.PARTnumber,
PO.POnumber,
PO.QTY,
PO.DOCKdate,
@ONorderQTYrunner:= @ONorderQTYrunner + PO.QTY AS RUNNINGtotal
FROM PURCHASEorders PO
WHERE PO.PARTnumber = @PARTnumber
ORDER BY PO.DOCKdate ASC
编辑: Gordon Linoff 的以下建议使用此方法代替内联变量赋值已更正该问题:
SUM(PO.QTY) OVER (ORDER BY PO.DOCKdate) as RUNNINGtotalfollowing
已更正运行总结果:
1 57 A-123 69 4000 2020-06-10 4000
2 32 A-123 67 500 2020-07-01 4500
3 59 A-123 69 2000 2020-07-15 6500
4 60 A-123 69 2000 2020-08-15 8500
结果,问题的根本原因: 已弃用的内联变量赋值。 注意:这是MySql和MariaDB中的问题
MySQLSELECT
语句中的变量赋值现已弃用。 使用适当的累积总和:
SELECT DISTINCT
ROW_NUMBER() OVER (ORDER BY DOCKdate ASC) AS ONorderROWindex,
PO.UniKey, PO.PARTnumber, PO.POnumber, PO.QTY, PO.DOCKdate,
SUM(PO.QTY) OVER (ORDER BY PO.DOCKdate) as RUNNINGtotal
FROM PURCHASEorders PO
WHERE PO.PARTnumber = @PARTnumber
ORDER BY PO.DOCKdate ASC;
我怀疑是否真的需要SELECT DISTINCT
,但那将是另一回事。