I have a table:
Comments (Id int identity primary key, PersonId Int(6), Comment1 Char(60))
The field Comment1 is supposed to contain nonessential comments only, however the field has been used to store nonessential comments but also important dates in the format dd/mm/yyyy.
So for example, the data in the table appears like the following:
* Id * PersonId * Comment1 *
| 1 | 5 | Likes Chocolate |
| 2 | 5 | 19/05/1992 |
| 3 | 5 | 23/07/1999 |
| 4 | 5 | 05/06/1994 |
| 5 | 8 | 07/12/1998 |
| 6 | 8 | Is very Tall |
| 7 | 8 | 24/05/1995 |
| 8 | 8 | 16/10/2002 |
| 9 | 11 | 13/11/2005 |
| 10 | 11 | 21/09/2000 |
| 11 | 11 | 8/99/100/23-1 |
SQL Fiddle
They now need to find the one row for each person which contains the most recent date in the Comment1 field.
Firstly I tried to remove those rows which did not contain a valid date using the following Query:
Select
Id,
PersonId,
Case
When IsDate(Comment1) = 1
Then convert(date, cast(rtrim(Comment1) as nvarchar), 103)
Else NULL
End
From Comments
But this only returned me:
* Id * PersonId * Comment1 *
| 4 | 5 | 1994-06-05 |
| 5 | 8 | 1998-12-07 |
The other rows being (null). This can be seen in the SQL Fiddle link.
Could some one please tell me where I’m going wrong?
Once this select statement returns what I require I expect I should be able to return the most recent date per PersonId using an aggregate function.
Use SET DATEFORMAT
SQL Fiddle