SQL Server 2008日期排除

时间:2013-11-11 22:28:02

标签: sql-server-2008

我正在试图找出一种方法来执行查询,该查询将获得超过六个月的所有数据,而不会有任何更新的数据。我会看看我是否可以恰当地总结一下:

select u.USER_FirstName, u.USER_LastName, 
    u.USER_LastSession, c.Login_Name

FROM USER u
   JOIN Customer c
      ON u.USER_Customer_Identity=c.Customer_Identity

Where u.USER_LastSession < getdate()-180

Order by USER_LastSession

这是我到目前为止在SO上发现的,但问题在于USER.USER_LastSession记录了每个登录的值(因此一些Customer.Login_Name值不需要返回)。我想要超过六个月的那些,如果在少于六个月的时间记录,则不会返回任何结果。示例数据:

USER_LastSession Login_Name

2012-08-29 21:33:30.000 TEST / TEST

2012-12-25 13:12:23.346示例/示例

2013-10-30 17:13:45.000 TEST / TEST

我不想返回TEST / TEST,因为过去六个月有数据。但是,我想返回EXAMPLE / EXAMPLE,因为它只有超过六个月的数据。我想可能有些东西我忽略了 - 请原谅我,如果已有答案(我只能找到“超过六个月的回复”)。非常感谢任何和所有的帮助!

2 个答案:

答案 0 :(得分:0)

SELECT ...
FROM User u
JOIN Customer c ON u.USER_Customer_Identity=c.Customer_Identity
WHERE u.USER_Customer_Identity NOT IN
    (SELECT USER_Customer_Identity
     FROM User
     WHERE USER_LastSession >= getdate() - 180)
ORDER BY USER_LastSession

答案 1 :(得分:0)

with cte as (
    select Login_Name, max(USER_LastSession) LastSession
    FROM USER u
    JOIN Customer c
        ON u.USER_Customer_Identity = c.Customer_Identity
    group by Login_Name
)

select *
from cte
where LastSession < getdate()-180