2

次のようなテーブルがあります。

Book        ¦Time Out       ¦Time In 
123456789   ¦01/01/2013 ¦07/07/2013
123456788   ¦15/01/2013 ¦20/01/2013
123456788   ¦23/01/2013 ¦30/01/2013
123144563   ¦01/02/2013 ¦18/02/2013
123144563   ¦20/02/2013 ¦NULL
124567892   ¦03/03/2013 ¦10/03/2013

次のようにしたいと思います。

Book        ¦Time Out       ¦Time In        ¦Next Time Out
123456789   ¦01/01/2013     ¦07/07/2013     ¦NULL
123456788   ¦15/01/2013     ¦20/01/2013     ¦23/01/2013
123456788   ¦23/01/2013     ¦30/01/2013     ¦NULL
123144563   ¦01/02/2013     ¦18/02/2013     ¦20/02/2013
123144563   ¦20/02/2013     ¦NULL           ¦NULL
124567892   ¦03/03/2013     ¦10/03/2013     ¦NULL

コード:

SELECT nextout.Book,
       nextout.[Time In] AS NextTimeIn
FROM   BookTable nextout
       JOIN BookTable nextoutsec
         ON nextout.Book = nextoutsec.Book
WHERE  nextout.[Time In] = (SELECT MAX(maxtbl.[Time In])
                            FROM   BookTable maxtbl
                            WHERE  maxtbl.Book = nextout.Book) 

これは、重複するブック ID の同じ「次回のタイムアウト」を返します。1 つの正しい値と 1 つの null 値ではなく。

ありがとう!

4

4 に答える 4

0

相関集計サブクエリを使用することもできます。

SELECT
  this.Book,
  this.[Time Out],
  this.[Time In],
  [Next Time Out] = (
    SELECT MIN(next.[Time Out])
    FROM BookTable next
    WHERE next.Book = this.Book
      AND next.[Time Out] > this.[Time Out]
  )
FROM BookTable this
;

これは@xanatos の提案のバリエーションと見なすことができますが、より軽量になる可能性があります。

于 2013-08-09T19:31:57.490 に答える