-1

我已经为此困扰了一段时间。Request#、SlotId、Segment 和 Version 都构成了主键。我想要从我的存储过程中获得的是能够通过传入请求#和段来检索所有行,但是对于每个插槽,我想要今天或之前的最新生效日期,并且我需要最高版本#。我感谢你的时间。

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 和为段传入 A 时,我想从我的存储过程中返回的值。

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

2 回答 2

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 ;
于 2012-12-03T22:53:27.057 回答
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    
于 2012-12-03T23:07:48.247 回答