达到总和后停止SQL选择

发布于 2025-01-26 01:02:59 字数 649 浏览 3 评论 0原文

我的数据库是IBM i的DB2。

我有只读访问权限,因此我的查询必须仅使用基本的SQL选择命令。

=============================================== ============

目标:

我想选择表中的每个记录,直到金额列的总和超过预定限制为止。

示例:

我想匹配表下的每个项目,直到“价格”列中的匹配值和$ 9.00。

所需的结果:

”在此处输入图像说明“

这可能吗?

My database is Db2 for IBM i.

I have read-only access, so my query must use only basic SQL select commands.

==============================================================

Goal:

I want to select every record in the table until the sum of the amount column exceeds the predetermined limit.

Example:

I want to match every item down the table until the sum of matched values in the "price" column >= $9.00.

enter image description here

The desired result:

enter image description here

Is this possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

半夏半凉 2025-02-02 01:02:59

您可以使用sum分析函数来计算运行总计的总价格,然后按其值过滤:

  AS(
  选择
    t。*,
    总和(价格)超过(按salesid ass订购)作为price_rsum
  从t
)
选择 *
来自
price_rsum< = 9
 
 salesid |价格| Price_rsum
------:| ----:| ------------:
   1001 | 5 | 5
   1002 | 3 | 8
   1003 | 1 | 9

db<> fiddle

You may use sum analytic function to calculate running total of price and then filter by its value:

with a as (
  select
    t.*,
    sum(price) over(order by salesid asc) as price_rsum
  from t
)
select *
from a
where price_rsum <= 9
SALESID | PRICE | PRICE_RSUM
------: | ----: | ---------:
   1001 |     5 |          5
   1002 |     3 |          8
   1003 |     1 |          9

db<>fiddle here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文