2014-01-31 54 views
0

我有一個表:Sum函數2008

PropertyID  Amount   
-------------------------- 
    1    40     
    1    20     
    1    10      
    2    10     
    2    90    

我想實現:

PropertyId  Amount Total_Amount 
    ---------------------------------------  
     1    40  70 
     1    20  70 
     1    10  70 
     2    10  100 
     2    90  100 

使用下面的查詢:

SELECT 
    PropertyID, 
    SUM(Amount), 
    SUM(TotalAmount) 
FROM 
    yourTable 
WHERE 
    EndDate IS NULL 
GROUP BY 
    PropertyID 

輸出:

PropertyId  Amount TotalAmount 
    -------------------------------------  
     1    70  70 
     2    100  100 

讓我知道我能得到我想要的輸出...

+0

什麼版本的SQL Server? –

回答

5

您可以使用窗口函數做到這一點:

select PropertyID, Amount, 
     sum(Amount) over (partition by PropertyId) as TotalAmount 
from yourtable; 

窗口功能sum()執行以下步驟。它計算同一組中行的組數的總和amount。該組由partition by子句定義,因此具有相同值PropertyId的行位於同一組中。

+0

應該有一個分組? – Jaques

+0

@Jaques。 。 。不應該有'分組'。感謝您注意它。 –

0
SELECT PropertyID, 
    Amount, 
    (select sum(yt.Amount) 
     from yourTable yt where yt.PropertyID==y.PropertyID and yt.EndDate IS NULL) 
    as TotalAmount 
    FROM yourTable y 
    WHERE y.EndDate IS NULL