get only 1 row from payment table

Simon Edri 1 Reputation point
2021-10-11T13:36:00.217+00:00

hi there ,
i have this query

Select 
C.CID,C.NID,C.FirstName,C.LastName,C.ID,
PM.AccountNum,PM.Balnce,PM.DateFrom,PM.DateTo,PM.MoveSum,PM.OpenDate,PM.ExportDate,PM.Rem,
PT.PayTypeName,
P.PayID, P.OpenDate
From Customers C  
LEFT JOIN PaymentsMoves PM ON C.CID = PM.CID
LEFT JOIN (SELECT TOP 1 PayID , OpenDate, PayDate, CID, PaySum FROM Payments GROUP BY PayID,OpenDate, PayDate, CID, PaySum) 
P ON P.CID = C.CID AND PM.CID IS NULL
LEFT JOIN PayType PT ON PT.PID = PM.MoveType

from the Payments table I want to get only the max row from each CID how can I get it ?
thanks ...

Developer technologies Transact-SQL
SQL Server Other
{count} votes

1 answer

Sort by: Most helpful
  1. EchoLiu-MSFT 14,621 Reputation points
    2021-10-12T01:44:15.527+00:00

    Hi @Simon Edri

    Welcome to the microsoft TSQL Q&A forum!

    Please try:

     Select   
     C.CID,C.NID,C.FirstName,C.LastName,C.ID,  
     PM.AccountNum,PM.Balnce,PM.DateFrom,PM.DateTo,PM.MoveSum,PM.OpenDate,PM.ExportDate,PM.Rem,  
     PT.PayTypeName,  
     P.PayID, P.OpenDate  
     From Customers C    
     LEFT JOIN PaymentsMoves PM ON C.CID = PM.CID  
     LEFT JOIN (SELECT * FROM (SELECT PayID , OpenDate, PayDate,CID, PaySum,   
                MAX(CID) OVER(PARTITION BY PayID) mm   
                FROM Payments) t  
                WHERE CID=mm) P  
     ON P.CID = C.CID AND PM.CID IS NULL  
     LEFT JOIN PayType PT ON PT.PID = PM.MoveType  
    

    If this does not solve your problem, please share us your table structure (CREATE TABLE …) and some sample data(INSERT INTO …)along with your expected result.So that we’ll get a right direction and make some test.

    If you have any question, please feel free to let me know.
    If the response is helpful, please click "Accept Answer" and upvote it.

    Regards
    Echo


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.