gpt4 book ai didi

sqlite - sqlite 选择行,直到在列中满足总数

转载 作者:行者123 更新时间:2023-12-03 15:18:26 25 4
gpt4 key购买 nike

我已经看到了 mysql 的类似问题,但我几乎找不到任何解决 sqllite 问题的方法。

我的 sample 表,

-----------------------------
ID | Product Name | Price
-----------------------------
1 A 2
2 B 2
3 C 1
4 D 3
5 E 2

在这里,我需要获取行,直到价格列的总数按升序等于或小于 5。

最佳答案

您可以使用 Product ID 进行运行总计和 ORDER BY Product ID像下面的一个:

SELECT p1.ID, p1.ProductName, p1.Price,
(SELECT SUM(p2.Price) FROM Products p2 WHERE p1.ID >= p2.ID ORDER BY p2.ID ) as RunningTotal
FROM Products p1
WHERE RunningTotal <= 5
ORDER BY p1.ID

Fiddle Demo

或使用 PriceORDER BY Price像下面的一个:
SELECT p1.ID, p1.ProductName, p1.Price, 
(SELECT SUM(p2.Price) FROM Products p2 WHERE p1.Price >= p2.Price ORDER BY Price )
as RunningTotal
FROM Products p1
WHERE RunningTotal <= 5
ORDER BY p1.Price;

2nd Fiddle Demo

关于sqlite - sqlite 选择行,直到在列中满足总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20159292/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com