根据特定ID获取以前记录的总和

时间:2014-02-28 09:27:39

标签: sql-server

如何根据特定ID获取以前的值 样本表

PrimaryIdId  RefId       Amount
1             5           150
2             5           100
3             5           10

我需要一个输出作为前一个金额的总和如下

Id         Amount      PreviousValue
--------------------------------------
1          150             - 
2          100             150
3          100             250  

之前记录的总和。

4 个答案:

答案 0 :(得分:0)

试试这个

select 
     PrimaryIdId ,
     Amount ,
     (select sum(Amount) from Table1 where PrimaryIdId < d.PrimaryIdId )  as PreviousValue
from Table1 d group by PrimaryIdId 

答案 1 :(得分:0)

SQL Server 2012

SELECT
    ID, Amount,
    SUM(Prev) OVER (ORDER BY ID RANGE UNBOUNDED PRECEDING)
FROM
    (
    SELECT
         PrimaryID AS ID,
         Amount,
         LAG(Amount) OVER (ORDER BY PrimaryID) AS Prev
    FROM
        dbo.Foo
    ) X;

如果你想要系列 per RefId 那么

SELECT
    ID, Amount, RefId,
    SUM(Prev) OVER (PARTITION BY RefId ORDER BY ID RANGE UNBOUNDED PRECEDING)
FROM
    (
    SELECT
         PrimaryID AS ID, RefId,
         Amount,
         LAG(Amount) OVER (PARTITION BY RefId ORDER BY PrimaryID) AS Prev
    FROM
        dbo.Foo
    ) X;

答案 2 :(得分:0)

这样的东西?

SELECT S.PrimaryIdId, S.Amount, CA.PreviousValue
FROM SampleTable S
OUTER APPLY 
   (SELECT SUM(Amount) PreviousValue
   FROM SampleTable S2 WHERE S2.RefId = S.RefId AND S2.PrimaryIdId < S.PrimaryIdId) CA

当然,我有一种感觉,你将拥有多套不同的RefId,使得结果无法识别。所以你可能想要更多的东西:

SELECT S.PrimaryIdId, S.RefId, S.Amount, CA.PreviousValue
FROM SampleTable S
OUTER APPLY 
   (SELECT SUM(Amount) PreviousValue
   FROM SampleTable S2 WHERE S2.RefId = S.RefId AND S2.PrimaryIdId < S.PrimaryIdId) CA
ORDER BY S.RefId, S.PrimaryIdId ASC

如果你有SQL Server 2012,你可以使用LAG功能。

答案 3 :(得分:0)

 ;WITH cte
     AS (SELECT 1   PrimaryId,
                5   RefId,
                150 Amount
         UNION ALL
         SELECT 2,
                5,
                100
         UNION ALL
         SELECT 3,
                5,
                100),
     cte1
     AS (SELECT *,
                0 AS amt
         FROM   cte a
         WHERE  primaryid = 1
         UNION ALL
         SELECT a.*,
                b.amount + amt
         FROM   cte a
                INNER JOIN cte1 b
                        ON a.primaryid - b.primaryid = 1)
SELECT *
FROM   cte1