2011-11-29 109 views
2
user table 
.--------------------------------. 
| userid| val | Create_Date  | 
.--------------------------------. 
| U1 | foo | 2011-05-01  | 
| U1 | foo | 2011-11-18  | 
|  |  |     | 
| U2 | foo | 2011-11-18  | 
| U2 | foo | 2011-11-28  | 
|  |  |     | 
| U3 | foo | 2011-04-11  | 
| U3 | foo | 2011-11-04  | 
|  |  |     | 
| U4 | foo | 2011-11-21  | 
| U4 | foo | 2011-11-28  | 
.________________________________. 

我有一个类似于上面的表。我需要得到的是最新的记录,并确保最新记录超过当前日期的5天。SQL查询帮助请求

例如,当前日期是2011-11-29

的SQL语句的输出应该

.--------------------------------. 
| userid| val | Create_Date  | 
.--------------------------------. 
| U3 | foo | 2011-11-04  | 
| U1 | foo | 2011-11-18  | 
.________________________________. 

我现在的SQL是能够得到最新的记录,但无法比较最新的日期。

请帮我调试。谢谢。

SELECT * FROM user_table t1 
WHERE DATEDIFF(NOW(), (SELECT MAX(create_date) 
       FROM user_table t2 
       WHERE t2.userid = t1.userid)) > 5 

在此先感谢。

+1

你要选择现在和5日龄之间带有日期超过过去5天或最后的记录日期? – Qqwy

+0

抱歉,如果这不够清楚。但我想要的是获得超过5天的记录。 – kevin

回答

1

您可以使用子查询为每个用户过滤较旧的记录。然后你可以使用where条件来要求最近的记录超过五天。

select * 
from UserTable u 
join (
     select userid 
     ,  max(Create_Date) as LatestCreateDate 
     from YourTable 
     group by 
       userid 
     ) filter 
on  filter.userid = u.userid 
     and filter.LatestCreateDate = u.Create_Date 
where datediff(now(), u.Create_Date) > 5 
+0

谢谢!正是我需要的 – kevin

0

尝试:

select user_id, val, min(Create_date) 
from table 
group by user_id 
having datediff(now(), min(Create_date)) > 5