按最近日期和最高版本选择所有列

时间:2012-12-03 22:37:49

标签: sql-server-2008

我被困在这一段时间了很长一段时间。请求#,SlotId,Segment和Version都构成主键。我想从我的存储过程中获得的是能够通过传递Request#和Segment来检索所有行,但是对于每个插槽,我想要在今天或之前的最近生效日期,并且我需要最高版本#。我赞美你的时间。

Values in database
Request#  SlotId  Segment Version Effective Date  ContentId
 A123       1       A       1         2012-01-01      1
 A123       2       A       1         2012-01-01      2 
 A123       2       A       2         2012-02-01      34
 A123       2       A       3         2012-02-01      24
 A123       2       A       4         2015-01-01      6 //beyond todays date. dont want

当我在A123中传递Request#和A for Segment时,我想从存储过程返回值。

 A123       1       A       1         2012-01-01      1
 A123       2       A       3         2012-02-01      24

2 个答案:

答案 0 :(得分:1)

查询可以这样写:

; WITH cte AS
    ( SELECT Request, SlotId, Segment, Version, [Effective Date], ContentId,
             ROW_NUMBER() OVER ( PARTITION BY Request, Segment, SlotId
                                 ORDER BY Version DESC ) AS RowN
      FROM
            tableX
      WHERE
            Request = @Req  AND  Segment = @Seg             --- the 2 parameters
        AND [Effective Date] < DATEADD(day, 1, GETDATE())
    )
  SELECT Request, SlotId, Segment, Version, [Effective Date], ContentId
  FROM cte
  WHERE Rn = 1 ;

答案 1 :(得分:0)

考虑一下:

;
WITH A as
(
   SELECT DISTINCT
       Request
   ,   Segment
   ,   SlotId
   FROM Table1
)
SELECT A.Request
 ,    A.SlotId
 ,    A.Segment
 ,    B.EffectiveDate
 ,    B.Version
 ,    B.ContentID
   FROM   A
     JOIN (
        SELECT  Top 1 
            Request
        ,   SlotId
        ,   Segment
        ,   EffectiveDate
        ,   Version
        ,   ContentId
        FROM  Table1 t1
        WHERE  t1.Request = A.Request
           AND t1.SlotId = A.SlotId
           AND T1.Segment = A.Segment
           AND T1.EffectiveDate <= GetDate()
        ORDER BY
           T1.EffectiveDate DESC
        ,  T1.Version DESC
    ) as B
       ON  A.Request = B.Request
       AND A.SlotId = B.SlotId
       AND A.Segment = B.Segment