Reputation: 1011
I have a table
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)
)
I want to select sum of Amount,RecAmount group by PartyId and I also want to select Last Outstanding entry of each PartyID. For this i use following query.
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
But i am unable to achieve the sum of Amount,RecAmount and Last Outstanding Record of each Party. Can someone help me here.
This is the Answer i got.
Upvotes: 0
Views: 67
Reputation: 3351
Assuming your records are inserted in tblPay.CID
order, use a subquery
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
or an 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
or, as JamieD77 suggests in his answer, use a CTE.
Upvotes: 2
Reputation: 13949
use a cte to get your tblPay information and join that to your other tables on the last record
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
Upvotes: 2