首页 > 解决方案 > 布尔值是否大于 x?

问题描述

对大家来说很有趣的问题。这是我的数据集示例(见下文)。我有仓库、日期以及给定仓库在该特定日期的库存水平变化

例如:假设 2018 年 1 月 1 日是第一个日期,仓库 1 开始时有 100 个库存,然后是 600,然后是 300,然后是 500...等等。

我想用 SQL 回答我的问题:按仓库 ID,每个仓库的库存是否超过 750(是/否)?

我无法对整个列求和,因为期末库存(按仓库列的总和)可能低于过去的库存水平。任何帮助表示赞赏!

+--------------+------------+---------------+
| Warehouse_id |    Date    | Inventory_Amt |
+--------------+------------+---------------+
|            1 | 1/1/2018   | +100          |
|            1 | 6/1/2018   | +500          |
|            1 | 6/15/2018  | -300          |
|            1 | 7/1/2018   | +200          |
|            1 | 8/1/2018   | -400          |
|            1 | 12/15/2018 | +100          |
|            2 | 1/1/2018   | +10           |
|            2 | 6/1/2018   | +50           |
|            2 | 6/15/2018  | -30           |
|            2 | 7/1/2018   | +20           |
|            2 | 8/1/2018   | -40           |
|            2 | 12/15/2018 | +10           |
|            3 | 1/1/2018   | +100          |
|            3 | 6/1/2018   | +500          |
|            4 | 6/15/2018  | +300          |
|            4 | 7/1/2018   | +200          |
|            4 | 8/1/2018   | -400          |
|            4 | 12/15/2018 | +100          |
+--------------+------------+---------------+

标签: sqlsql-servertsql

解决方案


You want a cumulative sum and then filtering:

select i.*
from (select i.*, sum(inventory_amt) over (partition by warehouse_id order by date) as inventory
      from inventory i
     ) i
where inventory_amt > 750

推荐阅读