Click here to Skip to main content
15,886,110 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to compare two dates in the same table. I am trying to compare them to see which is the most recent date. I see the CAST() and MAX(), but I'm not sure as to how to compare them in the manner of which is the most recent.
We have a page in an internal system that displays events. We need to do a reporting page, but we only want to pull the most recent dates based on the item. If we have 3 different instances of that item with different dates, I would need to know its last known record based upon the date. First date field is to the customer and the other is from the customer. Using MAX() is pulls up a record and then sticks the last known date in the date field, which we do not want. The last known date will be displayed, but we are needing to compare the dates for that particular date and then pull the record with that date, not the other two records.
Posted
Updated 9-Oct-15 7:46am
v2
Comments
PIEBALDconsult 9-Oct-15 13:42pm    
You'll need to Improve the question -- add detail and context, maybe some simplified example data.

1 solution

Assuming you're using a DBMS that supports it, the ROW_NUMBER function[^] is what you're looking for:
SQL
WITH cteOrderedResults As
(
    SELECT
        SomeColumns,
        ROW_NUMBER() OVER (PARTITION BY Customer ORDER BY TheDate DESC) As RN
    FROM
        YourTable
)
SELECT
    SomeColumns
FROM
    cteOrderedResults
WHERE
    RN = 1
;


NB: For future reference, always specify which DMBS you are using, including the version number. Also, it helps to include the basic structure of your table, and some example data. If possible, use SQLFiddle[^] to create a small sample of the problem.
 
Share this answer
 
Comments
Jonathan Cook 9-Oct-15 15:53pm    
Thank you. It is a MySQL DB.

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