如何使此查询返回审计表中的最新记录(MSSQL 2008)

时间:2013-10-08 13:36:35

标签: sql sql-server sql-server-2008

我已经看了几个关于此问题的答案,但由于我甚至不是非常接近业余DBA,所以他们有点过头了。谈论cte和一些我从未见过的内置函数。我想知道是否有一个更简单的解决方案,我想找到什么。这是我的疑问:

SELECT DISTINCT systudent.lastname, 
                systudent.firstname, 
                ...
                systatchange.effectivedate AS StatusChangeDate 
FROM   systudent 
       INNER JOIN systatchange 
               ON systudent.systudentid = systatchange.systudentid 
       INNER JOIN syschoolstatus 
               ON systudent.syschoolstatusid = syschoolstatus.syschoolstatusid 
       INNER JOIN amleadsrc 
               ON systudent.amleadsrcid = amleadsrc.amleadsrcid 
       INNER JOIN amleadtype 
               ON systudent.amleadtypeid = amleadtype.amleadtypeid 
       INNER JOIN sycountry 
               ON systudent.sycountryid = sycountry.sycountryid 
       INNER JOIN adprogram 
               ON systudent.adprogramid = adprogram.adprogramid 
WHERE  systatchange.effectivedate >= Dateadd(day, -7, Getdate()) 
       AND systatchange.newsyschoolstatusid = 1 --Lead 
       AND syschoolstatus.descrip NOT IN ( 
           '56-Future Graduate', '92-Application Denied' ) 
       AND amleadtype.code <= 'HS2014' 
ORDER  BY leaddate DESC 

我正在收集有关过去两周内状态更改为“1”(SyStatChange.NewSySchoolStatusID)的人的信息。

我遇到的问题是,对于某些用户,状态更改审核表显示重复记录。它们都有正确的状态更改字段,但有效日期是毫秒到分钟,所以我得到了欺骗。因此对于用户1 2和3,我只想要每个用户的最新记录。

最简单的方法是什么只能获取最近日期更改的记录上的SyStatChange信息?

1 个答案:

答案 0 :(得分:2)

使用CTEROW_NUMBER()功能可能是最简单的方式。

WITH CTE AS 
(
    --note that you shouldn't use DISTINCT
    SELECT systudent.lastname, 
           systudent.firstname, 
           ...
           ROW_NUMBER() OVER (PARTITION BY systudent.systudentid 
                              ORDER BY systatchange.effectivedate DESC
                             ) as RN
           --Partition by on whatever is your unique/id column (or columns)
    FROM ... --your tables
    WHERE ... --your conditions
    --no order here
)
SELECT * FROM CTE
WHERE RN = 1
ORDER BY leaddate DESC 

PS:请尝试为您的表使用别名而不是全名。它将使您的查询更具可读性。