从 Excel 到 SQL 实现 SUMIF() 函数

Implementing SUMIF() function from Excel to SQL

最近,我一直在学习如何使用 SQL 来处理数据。通常,我会为此目的使用 Python,但是 类 需要 SQL,而且我仍然很难在更复杂的场景中舒适地使用它。

我想要达到的效果与Excel中的以下截图相同:

Behaviour in Excel, that I want to implement in SQL

我在Excel中使用的公式:

=SUMIF(B:B2;B2;C:C2)

table 样本:

> select * from orders limit 5;
+------------+---------------+---------+
| ID         | clientID      | tonnage |
+------------+---------------+---------+
| 2005-01-01 | 872-13-44-365 |      10 |
| 2005-01-04 | 369-43-03-176 |       2 |
| 2005-01-05 | 408-24-90-350 |       2 |
| 2005-01-10 | 944-16-93-033 |       5 |
| 2005-01-11 | 645-32-78-780 |      14 |
+------------+---------------+---------+

实施应该 return 与以下 group by 查询类似的结果:

select
    orders.clientID as ID,
    sum(orders.tonnage) as Tonnage
from orders
group by orders.clientID;

即return每个客户购买了多少,但同时我希望将其return每一步的添加作为单独的记录。

例如:

客户 A 在第一笔订单中购买了 350,然后在第二笔订单中购买了 231。
在这种情况下,查询将 return 如下所示:

client A - 350 - 350 // first order
client A - 281 - 581 // second order

Example, how it would look like in Excel

我已经尝试过使用类似的东西:

select
    orders.clientID as ID,
    sum(case when orders.clientID = <ID> then orders.tonnage end)
from orders;

但很快就卡住了,因为我需要以某种方式动态更改此 <ID> 并将其值存储在某种临时变量中,我无法真正弄清楚如何在 SQL.

您可以使用 window 函数求和 运行。

在你的情况下,像这样使用

select id, clientID, sum(tonnage) over (partition by clientID order by id) tonnageRunning
from   orders

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=13a8c2d46b5ac22c5c120ac937bd6e7a