如何使用SQL将表中的开始日期更改为一对开始日期和结束日期

时间:2013-09-25 20:08:08

标签: sql sql-server sql-server-2012

标题必须令人困惑,但我试图做的事情很容易通过一个例子来理解。我有一张这样的桌子:

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的经验很少,我无法弄清楚如何。

请帮忙!谢谢!

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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