0

Im using SQL Server 2005. From the tbl_temp table below, I would like to add an EndDate column based on the next row's StartDate minus 1 day until there's a change in AID and UID combination. This calculated EndDate will go to the row above it as the EndDate. The last row of the group of AID and UID will get the system date as its EndDate. The table has to be ordered by AID, UID, StartDate sequence. Thanks for the help.

-- tbl_temp

AID     UID     StartDate
1   1   2013-02-20
2   1   2013-02-06
1   1   2013-02-21
1   1   2013-02-27
1   2   2013-02-02
1   2   2013-02-04

-- Result needed

AID     UID     StartDate        EndDate
1   1   2013-02-20       2013-02-20
1   1   2013-02-21       2013-02-26
1   1   2013-02-27       sysdate
1   2   2013-02-02       2013-02-03
1   2   2013-02-04       sysdate
2   1   2013-02-06       sysdate
4

2 に答える 2

1

これを行う最も簡単な方法は、相関サブクエリを使用することです。

select t.*,
       (select top 1 dateadd(day, -1, startDate )
        from tbl_temp t2
        where t2.aid = t.aid and
              t2.uid = t.uid and
              t2.startdate > t.startdate
       ) as endDate
from tbl_temp t

現在の日付を取得するには、次を使用しますisnull()

select t.*,
       isnull((select top 1 dateadd(day, -1, startDate )
               from tbl_temp t2
               where t2.aid = t.aid and
                     t2.uid = t.uid and
                     t2.startdate > t.startdate
               ), getdate()
              ) as endDate
from tbl_temp t

通常、私は以上をお勧めcoalesce()isnull()ます。ただし、SQL Serverの一部のバージョンには、最初の引数を2回評価するバグがあります。通常、これは違いを生みませんが、サブクエリを使用すると違いが生じます。

そして最後に、の使用はsysdate私にOracleについて考えさせます。同じアプローチがそこでも機能します。

于 2013-03-01T03:39:11.127 に答える
1
;WITH x AS
(
    SELECT AID, UID, StartDate, 
        ROW_NUMBER() OVER(PARTITION BY AID, UID ORDER BY StartDate) AS rn
    FROM tbl_temp
)
SELECT x1.AID, x1.UID, x1.StartDate, 
    COALESCE(DATEADD(day,-1,x2.StartDate), CAST(getdate() AS date)) AS EndDate
FROM x x1
LEFT OUTER JOIN x x2 ON x2.AID = x1.AID AND x2.UID = x1.UID
    AND x2.rn = x1.rn + 1
ORDER BY x1.AID, x1.UID, x1.StartDate

SQL フィドルの例

于 2013-03-01T03:42:47.547 に答える