窗口函数row\ u number()通过变量running total更改处理顺序

g2ieeal7  于 2021-07-29  发布在  Java
关注(0)|答案(1)|浏览(403)

当我使用窗口函数row\u number()添加一列时,我看到顺序发生了变化。
结果是运行总数不正确(@onorderqtyrunner)
有人能解释为什么行号()改变了排序顺序并导致运行total时出错吗?
下面的查询(带有行号())正在为第一行和第二行返回意外的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

如果没有行,则返回以下内容,如我所料:

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中的一个问题

9njqaruj

9njqaruj1#

mysql中的变量赋值 SELECT 现在不推荐使用语句。使用适当的累计和:

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 是真的需要,但那将是另一回事。

相关问题