0

我有一张桌子:

Comments (Id int identity primary key, PersonId Int(6), Comment1 Char(60))

该字段应该Comment1包含非必要的评论,但是该字段已用于存储非必要的评论以及 dd/mm/yyyy 格式的重要日期。

因此,例如,表中的数据如下所示:

* 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小提琴

他们现在需要为每个人找到包含该Comment1字段中最近日期的一行。

首先,我尝试使用以下查询删除那些不包含有效日期的行:

Select 
  Id,
  PersonId,
  Case 
    When IsDate(Comment1) = 1 
    Then convert(date, cast(rtrim(Comment1) as nvarchar), 103)
    Else NULL
  End
From Comments

但这只会让我回来:

* Id * PersonId *    Comment1     *
|  4 |        5 | 1994-06-05      |
|  5 |        8 | 1998-12-07      |

其他行是(null). 这可以在 SQL Fiddle 链接中看到。

有人可以告诉我哪里出错了吗?

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.

4

1 回答 1

3

Use SET DATEFORMAT

set dateformat dmy

Select 
  Id,
  PersonId,
  Case 
    When IsDate(Comment1) = 1 
    Then convert(date, cast(rtrim(Comment1) as nvarchar), 103)
    Else NULL 
  End
From Comments

SQL Fiddle

于 2013-01-07T10:33:28.973 回答