SQL自我加入标准

时间:2014-03-25 12:51:47

标签: sql-server-2008

我有一个表格,其中包含我希望在添加新列时加入的日期列表。我在下面粘贴了一个例子:

    Date
    03/03/2014
    03/03/2014
    03/03/2014
    04/03/2014
    04/03/2014
    04/03/2014
    04/03/2014

这是第一个表格,但是我想自己加入它,所以看起来像这样:

    Index_Date  Date
    03/03/2014  03/03/2014
    03/03/2014  03/03/2014
    03/03/2014  03/03/2014
    04/03/2014  03/03/2014
    04/03/2014  03/03/2014
    04/03/2014  03/03/2014
    04/03/2014  04/03/2014
    04/03/2014  04/03/2014
    04/03/2014  04/03/2014
    04/03/2014  04/03/2014

这只是数据的一个示例,但我很感激能够做到这一点的任何帮助!如果您还需要,请告诉我。

谢谢,Sam

以下是我汇总的一些测试代码:

    CREATE TABLE #DATES (Date VARCHAR (8))

    INSERT INTO #DATES VALUES ('20140303')
    INSERT INTO #DATES VALUES ('20140303')
    INSERT INTO #DATES VALUES ('20140303')
    INSERT INTO #DATES VALUES ('20140304')
    INSERT INTO #DATES VALUES ('20140304')
    INSERT INTO #DATES VALUES ('20140304')
    INSERT INTO #DATES VALUES ('20140304')

    SELECT
         T1.Date AS T1Date
,T2.Date AS T2Date
    FROM
 #DATES AS T1
        INNER JOIN #DATES AS T2 
        ON T1.Date = T2.Date

最终输出应为10行,如上所示。

2 个答案:

答案 0 :(得分:0)

以下是如何将表格加入自身

SELECT T1.Date as T1Date, T2.Date as T2Date
    FROM FooBar T1
    INNER JOIN FooBar T2 ON T1.Date = T2.Date

根据您的其他信息更新了您需要工会而不是自我加入:

DECLARE @firstDate DATETIME
DECLARE @secondDate DATETIME
SET @firstDate = '2014-03-03'
SET @secondDate = '2014-03-04'

SELECT @firstDate as Index_Date, Date FROM @Dates
       WHERE Date <= @firstDate
 UNION
SELECT @secondDate as Index_date, Date FROM @Dates
       WHERE Date <= @secondDate

如果需要,可以从另一个表中轻松加载两个日期参数。

这也应该为你提供你想要的没有 UNION:

SELECT ID.Index_Date, D.Date
     FROM IndexDateTable ID
    INNER JOIN Dates D ON D.Date <= ID.Index_Date

答案 1 :(得分:0)

select 
  dd.Date as T1Date,
  d.Date as T2Date
from
      (select distinct Date from Dates) as dd 
  left join Dates as d on d.Date <= dd.Date

请参阅http://sqlfiddle.com/#!3/4136c/6