Click here to Skip to main content
15,887,435 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi there,

I have the following dataset

ID_NO DateOfDeath PostDate
123 201501 201412
123 201501 201501
568 200601 201504
568 200601 201512

I need to select the ID_no when the DateOfDeath is equal to the PostDate. If it is not then it should select the ID_no with the maximum date.

The result should be:
ID_NO DateOfDeath PostDate
123 201501 201501
568 200601 201512
Posted
Comments
ZurdoDev 3-Feb-16 9:17am    
Probably just need a GROUP BY and possible a CASE statement in the WHERE clause. Where exactly are you stuck?

If we can assume that PostDate can never be greater than DateOfDeath then simple group by will do:
SQL
SELECT ID_NO, DateOfDeath, Max(PostDate) as PostDate FROM yourtable GROUP BY ID_NO, DateOfDeath
 
Share this answer
 
v3
Comments
Kornfeld Eliyahu Peter 3-Feb-16 9:48am    
Based on the samples it is exactly the other way around...PostDate is never smaller than DateOfDeath...
Tomas Takac 3-Feb-16 13:23pm    
Maybe it's my interpretation of dates but I see that always PostDate <= DateOfDeath (which kind of makes sense ;-)
ID_NO DateOfDeath PostDate
123 201501 > 201412
123 201501 = 201501
568 200601 > 201504
568 200601 > 201512
Kornfeld Eliyahu Peter 3-Feb-16 14:10pm    
You are right...For some reason on my phone it split a way made it look the exact opposite order...Now on the big screen it is strait...
Assuming Microsoft SQL Server, the ROW_NUMBER function[^] will do the trick:
SQL
WITH cteOrderedData As
(
    SELECT
        ID_NO,
        DateOfDeath,
        PostDate,
        ROW_NUMBER() OVER
        (
            PARTITION BY
                ID_NO
            ORDER BY
                CASE
                    WHEN DateOfDeath = PostDate THEN 0
                    ELSE 1
                END,
                PostDate DESC
        ) As RN
    FROM
        YourTable
)
SELECT
    ID_NO,
    DateOfDeath,
    PostDate
FROM
    cteOrderedData
WHERE
    RN = 1
;
 
Share this answer
 

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