1

标题一定很混乱,但我想做的事情很容易通过一个例子来理解。我有一张这样的桌子:

Code         Date_           Ratio

73245   Jan  1 1975 12:00AM    10
73245   Apr 18 2006 12:00AM    4
73245   Dec 26 2007 12:00AM    10
73245   Jan 30 2009 12:00AM    4
73245   Apr 21 2011 12:00AM    2

基本上,对于每种证券,它都会给出一些比率,以及该比率开始生效的日期。如果该表不仅具有开始日期,而且具有一对开始日期和结束日期,则该表将更易于使用,如下所示:

Code             StartDate_         EndDate_               Ratio
73245     Jan  1 1975 12:00AM   Apr 18 2006 12:00AM         10
73245     Apr 18 2006 12:00AM   Dec 26 2007 12:00AM          4
73245     Dec 26 2007 12:00AM   Jan 30 2009 12:00AM         10
73245     Jan 30 2009 12:00AM   Apr 21 2011 12:00AM          4
73245     Apr 21 2011 12:00AM   Dce 31 2049 12:00AM(or some random date in far future)           2

如何使用 SQL 语句将原始表转换为我想要的表?我对 SQL 的经验很少,我不知道怎么做。

请帮忙!谢谢!

4

2 回答 2

2

在 SQL Server 2012 中:

SELECT  code,
        date_ AS startDate,
        LEAD(date_) OVER (PARTITION BY code ORDER BY date_) AS endDate,
        ratio
FROM    mytable

在 SQL Server 2005 和 2008 中:

WITH    q AS
        (
        SELECT  *,
                ROW_NUMBER() OVER (PARTITION BY code ORDER BY date_) AS rn
        FROM    mytable
        )
SELECT  q1.code, q1.date_ AS startDate, q2.date_ AS endDate, q1.ratio
FROM    q q1
LEFT JOIN
        q q2
ON      q2.code = q1.code
        AND q2.rn = q1.rn + 1
于 2013-09-25T20:27:42.960 回答
0

也许也可以使用 OUTER APPLY,例如:

SELECT t1.Code, t1.Date_ AS StartDate_, ISNULL(t2.EndDate_, CAST('20491231' AS DATETIME)) AS EndDate_
FROM t1 AS t1o
OUTER APPLY
(
       SELECT TOP 1 Date_ AS EndDate_
       FROM t1 
       WHERE t1.Code = t1o.Code AND t1.Date_ > t1o.Date_
       ORDER BY t1.Date_ ASC
) AS t2
于 2013-09-25T20:46:04.490 回答