[英]SQL stored procedure to add up values and stop once the maximum has been reached
I would like to write a SQL query (SQL Server) that will return rows (in a given order) but only up to a given total. 我想写一个SQL查询(SQL Server),它将返回行(按给定的顺序),但只返回给定的总数。 My client has paid me a given amount, and I want to return only those rows that are <= to that amount.
我的客户已付给我一定的金额,我想只返回那些<=到那个金额的行。
For example, if the client paid me $370, and the data in the table is 例如,如果客户支付我370美元,表中的数据是
id amount
1 100
2 122
3 134
4 23
5 200
then I would like to return only rows 1, 2 and 3 那么我想只返回第1,2和3行
This needs to be efficient, since there will be thousands of rows, so a for loop would not be ideal, I guess. 这需要高效,因为会有数千行,所以for循环并不理想,我猜。 Or is SQL Server efficient enough to optimise a stored proc with for loops?
或者SQL Server是否足够高效以使用for循环优化存储过程?
Thanks in advance. 提前致谢。 Jim.
吉姆。
A couple of options are. 有两种选择。
1) Triangular Join 1)三角连接
SELECT *
FROM YourTable Y1
WHERE (SELECT SUM(amount)
FROM YourTable Y2
WHERE Y1.id >= Y2.id ) <= 370
2) Recursive CTE 2)递归CTE
WITH RecursiveCTE
AS (
SELECT TOP 1 id, amount, CAST(amount AS BIGINT) AS Total
FROM YourTable
ORDER BY id
UNION ALL
SELECT R.id, R.amount, R.Total
FROM (
SELECT T.*,
T.amount + Total AS Total,
rn = ROW_NUMBER() OVER (ORDER BY T.id)
FROM YourTable T
JOIN RecursiveCTE R
ON R.id < T.id
) R
WHERE R.rn = 1 AND Total <= 370
)
SELECT id, amount, Total
FROM RecursiveCTE
OPTION (MAXRECURSION 0);
The 2nd one will likely perform better. 第二个可能表现更好。
In SQL Server 2012 you will be able to so something like 在SQL Server 2012中,您将能够像这样
;WITH CTE AS
(
SELECT id,
amount,
SUM(amount) OVER(ORDER BY id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
AS RunningTotal
FROM YourTable
)
SELECT *
FROM CTE
WHERE RunningTotal <=370
Though there will probably be a more efficient way (to stop the scan as soon as the total is reached) 虽然可能会有更有效的方法(一旦达到总数就停止扫描)
Straight-forward approach : 直截了当的做法:
SELECT a.id, a.amount
FROM table1 a
INNER JOIN table1 b ON (b.id <=a.id)
GROUP BY a.id, a.amount
HAVING SUM(b.amount) <= 370
Unfortunately, it has N^2 performance issue. 不幸的是,它有N ^ 2性能问题。
something like this: 这样的事情:
select id from
(
select t1.id, t1.amount, sum( t2.amount ) s
from tst t1, tst t2
where t2.id <= t1.id
group by t1.id, t1.amount
)
where s < 370
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.