TSQL-加入自己的表,仅选择最新的行

时间:2011-09-27 08:56:43

标签: tsql sql-server-2008 join

我有一个表tbl_Partner(缩写),有两个“重复”的合作伙伴:

RecordID (GUID) | RISEID (varchar(40)) | UpdateCounter(int) | etc. ...
-----------------------------------------------------------
12345678-9012-3456-7890-123456789012 | RISE123 | 0
87564321-9012-3456-7890-123456789012 | RISE123 | 1
-- other partners with different updatecounters etc.

现在我需要一个视图,其中包含每个合作伙伴的最新数据(最高UpdateCounter),但第一个RecordID(最低UpdateCounter)

我已经尝试过这个SQL了:

select 
(select top 1 recordid from tbl_partner p2 where p2.riseid=p1.riseid order by p2.updatecounter ASC) as RecordID
, riseid, updatecounter
from tbl_partner p1
order by riseid

我明白了:

RecordID (GUID) | RISEID (varchar(40)) | UpdateCounter(int)
-----------------------------------------------------------
12345678-9012-3456-7890-123456789012 | RISE123 | 0 --(old data)
12345678-9012-3456-7890-123456789012 | RISE123 | 1 --(new correct data with the first RecordID)
-- other rows/columns omitted

如何仅为每个RecordID / RiseID选择最新行? (在此示例中,UpdateCounter = 1)

对于记录: UpdateCounter当然不是1,而且还有其他数据集具有不同的值。所以我不能使用简单的WHERE updatecounter>0

2 个答案:

答案 0 :(得分:2)

SELECT t1.RecordID,t1.RISEID,t2.UpdateCounter
FROM
   tbl_Partner t1
      inner join
   tbl_Partner t2
      on
          t1.RISEID = t2.RISEID
      left join
   tbl_Partner t1_anti
      on
          t1.RISEID = t1_anti.RISEID and
          t1_anti.UpdateCounter < t1.UpdateCounter
      left join
   tbl_Partner t2_anti
      on
          t1.RISEID = t2_anti.RISEID and
          t2_anti.UpdateCounter > t2.UpdateCounter
where
    t1_anti.RISEID is null and
    t2_anti.RISEID is null

目前尚不清楚是否要为只有一行具有特定RISEID的项目显示行。如果没有,请在t1t2之间的联接中添加额外条件,以使UpdateCounter上的t2更高。

两个外部联接是为了确保没有早于t1t1_anti)的行,而不是t2t2_anti)之后的行。在WHERE子句中,我们确保这些连接不成功。


替代,使用稍微更现代的风格:

;With OrderedRows as (
    Select RecordID,RISEID,UpdateCounter,
      ROW_NUMBER() OVER (PARTITION BY RISEID ORDER BY UpdateCounter ASC) as rnEarly,
      ROW_NUMBER() OVER (PARTITION BY RISEID ORDER BY UpdateCounter DESC) as rnLate
    from tbl_Partner
)
SELECT t1.RecordID,t1.RISEID,t2.UpdateCounter
FROM
   OrderedRows t1
       inner join
   OrderedRows t2
       on
            t1.RISEID = t2.RISEID
WHERE
    t1.rnEarly = 1 and
    t2.rnLate = 1

可能需要在桌面上扫描更少。

答案 1 :(得分:0)

选择Max UpdateCounter

 select distinct(
 (select top 1 recordid from tbl_partner p2 where p2.riseid=p1.riseid p2.updatecounter ASC
 ) )as RecordID,(select  Max(updatecounter) from tbl_partner p2 where p2.riseid=p1.riseid   ) as MaxUpdateCounter , riseid  from tbl_partner p1