在mysql中使用sum() over(Partition by)组合多行数据

Posted

技术标签:

【中文标题】在mysql中使用sum() over(Partition by)组合多行数据【英文标题】:Combine multiple row data using sum() over(Partion by) in mysql 【发布时间】:2019-07-11 16:15:57 【问题描述】:
SELECT orders.Stock ,lflayouts.sides, count(*) as Quantity FROM dash_relationship 
JOIN orders ON orders.UID = dash_relationship.form_id
JOIN lfitems ON lfitems.uid = orders.UID
Join lflayouts ON lflayouts.id = lfitems.layout_id
WHERE dash_relationship.machine_id='108'
GROUP BY orders.stock,lflayouts.sides;

以上查询输出如下

STOCK   SIDES    QUANTITY
paper1    1         214
paper1    2         210
paper2    1           7
paper3    1           2

现在我的问题是,如果我想获得基于不同方面的个股总数,该怎么办。所以我尝试使用下面的查询,它给我一个错误,说服务器版本在第 1 行的 '(partition) 附近使用正确的语法

SELECT orders.Stock ,lflayouts.sides, count(*) as Quantity, SUM(lflayouts.sides) OVER(partition by orders.stock) as Total FROM dash_relationship 
JOIN orders ON orders.UID = dash_relationship.form_id
JOIN lfitems ON lfitems.uid = orders.UID
Join lflayouts ON lflayouts.id = lfitems.layout_id
WHERE dash_relationship.machine_id='108'
GROUP BY orders.stock,lflayouts.sides;

EXPECTED OUTPUT
STOCK   SIDES    QUANTITY TOTAL
paper1    1         214    414 or 214
paper1    2         210    414
paper2    1           7      7
paper3    1           2      2

【问题讨论】:

那么你的 mysql 版本是多少?对于总计,我认为您需要 [partition by] 之后的 [order by] @GenWan MySQL 5.5.62 MySQL 从 8.0 版本开始支持窗口函数。 我尝试使用 order by inside (partition by orders.stock order by lflayouts.sides) 同样的错误 【参考方案1】:

MySQL 5.5.62 不支持窗口函数。

您可以使用标准连接来实现它,但查询看起来会更复杂。

SELECT    T1.Stock
         ,T1.sides
         ,Sum(T2.Quantity) as RunningTotal
FROM     (SELECT orders.Stock ,lflayouts.sides, count(*) as Quantity 
          FROM 
              dash_relationship 
              JOIN orders ON orders.UID = dash_relationship.form_id
              JOIN lfitems ON lfitems.uid = orders.UID
              JOIN lflayouts ON lflayouts.id = lfitems.layout_id
              WHERE dash_relationship.machine_id='108'
              GROUP BY orders.stock,lflayouts.sides
         ) T1
         INNER JOIN 
         (
          SELECT orders.Stock ,lflayouts.sides, count(*) as Quantity 
          FROM 
              dash_relationship 
              JOIN orders ON orders.UID = dash_relationship.form_id
              JOIN lfitems ON lfitems.uid = orders.UID
              JOIN lflayouts ON lflayouts.id = lfitems.layout_id
              WHERE dash_relationship.machine_id='108'
              GROUP BY orders.stock,lflayouts.sides
         ) T2
         ON   T1.sides >= T2.sides
         AND  T1.Stock = T2.Stock
GROUP BY  T1.Stock
         ,T1.sides
Order BY  T1.Stock
         ,T1.sides

【讨论】:

以上是关于在mysql中使用sum() over(Partition by)组合多行数据的主要内容,如果未能解决你的问题,请参考以下文章

如何在 mysql 5.7 中使用 sum over partition(无窗口函数)

SQL大圣之路笔记——SQL学习笔记

如何使“SUM(amount) over”窗口函数在 MySQL 5.7 中工作?

MySQL - SUM() OVER() 函数用法详解

MySQL 开窗函数

开窗函数