Click here to Skip to main content
15,886,919 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
InspNo					PartnerCode	CreaOn					IsPush	PushToPartner
I/2023/400018/00097602	MFC			2023-11-01 20:25:19.477	NULL	NULL
I/2023/400018/00097602	MFC			2023-11-01 20:06:18.480	NULL	NULL
I/2023/400018/00097601	ADR			2023-11-01 19:41:50.970	NULL	NULL
I/2023/400018/00097601	MFC			2023-11-01 19:33:18.303	NULL	NULL
I/2023/400018/00097601	ADR			2023-11-01 14:30:04.463	NULL	NULL
I/2023/400018/00097600	ADR			2023-10-31 16:29:09.950	NULL	NULL
I/2023/400015/00085384	ADR			2023-10-31 16:08:40.390	NULL	NULL


Above is my table.
What I want is the latest record inspection wise on the basis of partner code.

Excepted output
I want only 1 record Latest of I/2023/400018/00097601 and also only 1 record Latest of I/2023/400018/00097602 on this basis of Partner code.

I tried the following:

SQL
select InspNo,InputStr,PartnerCode,IsPush,CreaOn,IsPush,_
PushToPartner from PartnerIntegrationLog where IsPush is null _
and  (PartnerCode='ADR' OR PartnerCode='MFC') 
group by InspNo,InputStr,PartnerCode,IsPush,CreaOn,IsPush,_
PushToPartner
 order by CreaOn desc


But it gives duplicate record of both inspections.

What I have tried:

I tried many things but am not getting any success.
Posted
Updated 1-Nov-23 9:00am
v3

1 solution

That's not how GROUP BY works; you're grouping by every column, so unless there are two identical records in the table, it will return every record.

Probably the simplest option would be to use ROW_NUMBER to partition the records:
SQL
WITH cte As
(
    SELECT
        InspNo,
        InputStr,
        PartnerCode,
        CreaOn,
        IsPush,
        PushToPartner,
        ROW_NUMBER() OVER (PARTITION BY PartnerCode ORDER BY CreaOn DESC) As RN
    FROM
        PartnerIntegrationLog 
    WHERE
        IsPush Is Null
    And 
        (PartnerCode = 'ADR' OR PartnerCode = 'MFC')
)
SELECT
    InspNo,
    InputStr,
    PartnerCode,
    CreaOn,
    IsPush,
    PushToPartner
FROM
    cte
WHERE
    RN = 1
;
 
Share this answer
 
v2
Comments
M Imran Ansari 1-Nov-23 16:58pm    
Before executing the above query, make sure the column 'IsPush' was specified multiple times for 'cte'. remove the one entry of 'IsPush'
Richard Deeming 2-Nov-23 4:33am    
Good spot! That was copied from the query in the question. :)
Akshay malvankar 2-Nov-23 1:23am    
Thank you so much Ansari

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900