如何在一个查询中使用sum和max

时间:2016-12-13 13:09:58

标签: sql-server

我有一张桌子

tblPay
(
    CID bigint,
    PartyIdID bigint,
    PartyName varchar(50),
    AgentName varchar(50), 
    Agent bigint,
    Amount decimal(18,2),
    RecAmount decimal(18,2),
    OutStanding decimal(18,2)
)

我想通过PartyId选择Amount,RecAmount组的总和,我也想选择每个PartyID的Last Outstanding条目。为此,我使用以下查询。

SELECT  DISTINCT CID, 
        Party.AccLedger_ID PartyID, 
        Party.AccLedger_Name PartyName,
        Agent.AccLedger_Name AgentName,
        Agent.AccLedger_ID AgentID,
        sum(S.Amount) Amount,
        Sum(S.RecAmount) RecAmount,
        S.OutStanding 
Group by PartyID,
         Cid,
         Party.AccLedger_ID,
         Party.AccLedger_Name,
         Agent.AccLedger_Name,
         Agent.AccLedger_ID,
         S.OutStanding  

但是我无法达到各方的金额,重新安排和最后一次记录的总和。有人可以帮助我。

enter image description here

这是我得到的答案。

2 个答案:

答案 0 :(得分:2)

使用cte获取您的tblPay信息并将其加入到最后一条记录中的其他表格

WITH cte AS (
    SELECT 
        CID,
        PartyName,
        SUM(Amount) OVER (PARTION BY PartyIdID) Amount,
        SUM(RecAmount) OVER (PARTITION BY PartyIdID) RecAmount,
        OutStanding,
        -- only assuming your CID determines order since you have no date?
        ROW_NUMBER() OVER (PARTITION BY PartyIdID ORDER BY CID DESC) Rn 
    FROM tblPay
) 
SELECT  Party.*,
        Agent.*,
        p.CID,
        p.PartyName,
        p.Amount,
        p.RecAmount,
        p.Oustanding
FROM    Party JOIN Agent
        JOIN cte p ON p.PartyIdID = Party.AccLedger_ID AND p.Rn = 1

答案 1 :(得分:2)

假设您的记录以tblPay.CID顺序插入,请使用子查询

SELECT  p.PartyID,
        p.PartyName,
        SUM(p.Amount) AS PartyAmount,
        SUM(p.RecAmount) AS PartyRecAmount,
        (SELECT TOP 1 OutStanding FROM tblPay p2 WHERE p.PartyID = p2.PartyId ORDER BY CID DESC) AS LastOutStanding
FROM tblPay p
GROUP BY p.PartyID, p.PartyName

OUTER APPLY

SELECT  p.PartyID,
        p.PartyName,
        SUM(p.Amount) AS PartyAmount,
        SUM(p.RecAmount) AS PartyRecAmount,
        lastRecord.OutStanding AS LastOutStanding
FROM tblPay p
OUTER APPLY
(
    SELECT TOP 1 OutStanding
    FROM tblPay p2
    WHERE p.PartyID = p2.PartyId
    ORDER BY CID DESC
) lastRecord
GROUP BY p.PartyID, p.PartyName

或者,正如JamieD77在答案中建议的那样,使用CTE。