I have a table like:
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
I would like it to look like this:
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
Code:
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)
This returns for the duplicate book id's the same 'Next Time Out'. rather than 1 correct value and 1 null value.
Thank You!
Untested but something like the following should get you started
;WITH q as (
SELECT Book, [Time In], ROW_NUMBER() OVER (PARTITION BY Book ORDER BY [Time In]) AS rn
FROM BookTable
)
SELECT bt.*, q2.[Time In] AS NextTimeIn
FROM BookTable bt
INNER JOIN q q1 ON q1.Book = bt.Book AND ISNULL(q1.[Time In], 0) = ISNULL(bt.[Time In], 0)
LEFT OUTER JOIN q q2 ON q2.Book = q1.Book AND q2.rn = q1.rn + 1
The gist of this is
q
adds a row number to each book, ordered by [Time In]
q2
joins with q1
to get the next [Time In]
value.q1
joins with BookTable
to get all the original values이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다