关于更新表中的行而不使用循环

时间:2014-07-02 07:46:32

标签: sql-server

我有一个表,其中我有一个名为quantity的列,我有10行,它们具有相同的列值200(可以是任何值)

要求是:如果输入值是x = 500(或任何数字),则应将此值与下面的fasion中的数量列值进行比较: 如果1行的数量是200,那么它应该从500减去它,x应该更新为300,并且该行的数量应该为0然后它应该移动到下一行直到x为0

你能不能帮我写一下sql查询...

要求不要使用循环。

感谢,

2 个答案:

答案 0 :(得分:0)

SQL Server的版本是什么?如果是2012年或2014年,您可以使用以下内容:

DECLARE @x int = 500

;WITH cte_sum AS
(
    SELECT quantity,
       ISNULL(SUM(quantity) OVER (ORDER BY (SELECT NULL) ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING), 0) sum_running_before,
       SUM(quantity) OVER (ORDER BY (SELECT NULL) ROWS UNBOUNDED PRECEDING) sum_running_total
FROM YourTable
)
UPDATE cte_sum
SET quantity = CASE
                WHEN quantity >= @x - sum_running_before THEN
                     quantity - (@x - sum_running_before)
                ELSE 0
            END
WHERE (@x >= sum_running_total OR (@x < sum_running_total AND sum_running_before < @x))

在早期版本中获得运行总计会有点棘手,但我认为你有主要想法。

答案 1 :(得分:0)

DECLARE @YourTable TABLE
(
    CustId INT,
    Quantity INT
)

INSERT INTO @YourTable
( CustId, Quantity )
VALUES
( 1, 10 ),
( 1, 10 ),
( 1, 10 ),
( 1, 10 ),
( 2, 20 ),
( 2, 20 ),
( 2, 20 ),
( 2, 20 );

;WITH cte_sum AS
(
    SELECT 
        y.CustId,
        y.Quantity,
        ROW_NUMBER() OVER (PARTITION BY CustId ORDER BY Quantity) RN
    FROM @YourTable y
)
SELECT s1.CustId, s1.Quantity, s2.Qty, s1.Quantity + ISNULL(s2.Qty, 0) RunningTotal, s1.RN
FROM cte_sum s1
OUTER APPLY
(
    SELECT SUM(Quantity) Qty FROM cte_sum s2
    WHERE s2.CustId = s1.CustId
        AND s2.RN < s1.RN
) s2
ORDER BY s1.CustId, s1.RN

这是一个适用于Sql Server 2005 +

的运行总计的示例

这是输出:

CustId  Quantity    Qty RunningTotal    RN
1   10  NULL    10  1
1   10  10  20  2
1   10  20  30  3
1   10  30  40  4
2   20  NULL    20  1
2   20  20  40  2
2   20  40  60  3
2   20  60  80  4
相关问题