我一直在搜索StackOverflow,我找到的最接近的是to use custom variable inside subquery。但建议的解决方案有两个缺点。
+----+-------+-------------+
| id | type | MyAmountCol |
+----+-------+-------------+
| 1 | 85482 | 10 |
+----+-------+-------------+
| 2 | 47228 | 20 |
+----+-------+-------------+
| 3 | 12026 | 40 |
+----+-------+-------------+
SET @runningTotal=0;
SELECT
O.Id,
O.Type,
O.MyAmountCol,
@runningTotal + O.MyAmountCol as 'RunningTotal',
@runningTotal := @runningTotal + O.MyAmountCol
FROM Table1 O
HAVING RunningTotal <=5;
回
0 Row(s)
SET @runningTotal=0;
SELECT
O.Id,
O.Type,
O.MyAmountCol,
@runningTotal + O.MyAmountCol as 'RunningTotal',
@runningTotal := @runningTotal + O.MyAmountCol
FROM Table1 O
HAVING RunningTotal <=15;
回
1 85482 10 10 (1 Row)
期望的结果就是这样。在第一个例子中,我希望返回第一行(id = 1
,type = 85842
)。在第二个示例中,我想要ID = 1
,type = 85842
和id = 2
,返回类型= 47228
的行。
换句话说,我正在尝试做的与我发现的略有不同,并且似乎没有用这种方法实现它。我希望最少数量的连续行超过目标值。有没有办法只用MySQL(查询),或者我应该在应用程序级别解决这个问题?
答案 0 :(得分:1)
在较小的ID上将表连接到自身(因为这是您要订购的内容),将连接中的所有行相加并保持总和小于的行(不小于或等于门槛:
private void Button_Clicked_1(object sender, EventArgs e)
{
listViewJson.ItemTapped += ListViewJson_ItemTapped;
}
private void ListViewJson_ItemTapped(object sender, ItemTappedEventArgs e)
{
var focusing = e.Item;
listViewJson.ScrollTo(focusing, ScrollToPosition.MakeVisible, true);
}
添加SELECT
a.Id,
a.Type,
a.MyAmountCol
FROM Table1 a
LEFT JOIN Table1 b on b.id < a.id
GROUP BY 1,2,3
HAVING COALESCE(SUM(b.MyAmountCol), 0) < 15
调用以满足最低ID,我们希望保留(始终),没有要加入的行。
免责声明:代码可能无法编译或工作,因为它在我的手机上被翻阅(但它有可能起作用)