[英]sum columns in mysql from up to down rows and select the rows in which the value falls
[英]How to retrieve all rows from up to down in MySQL after sum to some specific value?
假設我在數據庫表中有這些類型的數據。 我如何執行查詢,例如當我傳遞某個值時,它應該從上到下的行求和並選擇求和該值所需的所有行。
當我傳遞值 11 時,它應該從上到下的行求和,並求和 id 為 1 2 3 的行,即 (3+2+7),因為 11 落在第三行范圍內,並選擇等於或大於該值的所有行。
假設我傳遞 20 個值,它應該對第 1 2 3 4 行求和,因為 20 落在 (3+2+7+10) 第 4 列中並選擇所有 4 行。
ID, TABLE_COLUMN
1,2
2,3
3,7
4,10
5,11
6,15
我試過這樣做並且它有效,但它似乎很慢。 當我在 20K 數據表中查詢時,檢索 10 行數據大約需要 20 秒甚至更多。
SELECT t1.ID, t1.TABLE_COLUMN
FROM yourTable t1
WHERE (SELECT COALESCE(SUM(t2.TABLE_COLUMN), 0)
FROM yourTable t2
WHERE t2.ID < t1.ID) < 20;
MySQL 版本是 5.7.12。 (Amazon AWS MySQL Aurora;這意味着我無法升級 MySQL 的版本)。
如果你運行的是 MySQL 8.0,你可以做一個窗口總和並通過它過濾:
select id, table_column
from (
select
t.*,
sum(table_column) over(order by id) wsm
from mytable t
) t
where wsm >= 20 and wsm - table_column < 20
order by id
在早期版本中,您的查詢對我來說似乎是一個合理的選擇。 為了性能,您需要(id, table_column)
上的索引。
或者,您可以嘗試使用用戶變量模擬窗口總和:
select id, table_column
from (
select
t.*,
@wsm := @wsm + table_colum wsm
from (select * from mytable order by id) t
cross join (select @wsm := 0) v
) t
where wsm >= 20 and wsm - table_column < 20
order by id
試試這個(用你需要的值替換 20):
SELECT * FROM yourtable y WHERE id <=
( SELECT MIN(id) FROM (
SELECT t1.id, t1.table_column,SUM(t2.table_column)running_total
FROM yourtable t1, yourtable t2
WHERE t2.id <= t1.id
GROUP BY t1.id,t1.table_column
) as i
WHERE i.running_total >= 20
)ORDER by y.id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.