交叉申请查找所有日期

时间:2014-06-23 09:30:02

标签: sql sql-server sql-server-2008

我有一张桌子会存储当前年份日期,我在该表格中也有一个开始日期。是否有可能使用CROSS APPLY获取当前日期和开始日期之间的所有日期。

Ex: 
Current_Year         Start_Date
2014-06-12           2011-01-01  
2014-04-12           2011-01-01 
2014-02-12           2011-01-01
2014-01-12           2011-01-01

I want result set like 

Year
2014-06-12           2011-01-01  
2014-04-12           2011-01-01 
2014-02-12           2011-01-01
2014-01-12           2011-01-01
2013-06-12           2011-01-01  
2013-04-12           2011-01-01 
2013-02-12           2011-01-01
2013-01-12           2011-01-01
2012-06-12           2011-01-01  
2012-04-12           2011-01-01 
2012-02-12           2011-01-01
2012-01-12           2011-01-01
2011-06-12           2011-01-01  
2011-04-12           2011-01-01 
2011-02-12           2011-01-01
2011-01-12           2011-01-01

3 个答案:

答案 0 :(得分:2)

以下将使用CROSS APPLY:

给出所需的结果
WITH T AS 
(   SELECT  Current_Year = CAST(cy AS DATE), Start_Date = CAST(sd AS DATE)
    FROM    (VALUES
                ('2014-06-12', '2011-01-01'),
                ('2014-04-12', '2011-01-01'),
                ('2014-02-12', '2011-01-01'),
                ('2014-01-12', '2011-01-01')
            ) t (cy, sd)
)
SELECT  Current_Year = DATEADD(YEAR, - n.Number, t.Current_Year),
        t.Start_Date
FROM    T
        CROSS APPLY 
        (   SELECT  TOP 1000 ROW_NUMBER() OVER (ORDER BY a.object_id) - 1
            FROM    sys.all_objects AS a
        ) AS n (Number)
WHERE   DATEADD(YEAR, - n.Number, t.Current_Year) > t.Start_Date;

但是,CROSS JOIN同样可以正常工作,并且可能在语义上更有意义,尽管执行计划最终会变得相同。

答案 1 :(得分:0)

DECLARE @TAB1 TABLE (CURRENT_YEAR DATE)
INSERT INTO @TAB1 VALUES('2014-06-12'),('2014-04-12'),('2014-02-12'),('2014-01-12')

DECLARE @TAB2 TABLE (CURRENT_YEAR DATE)
INSERT INTO @TAB2 VALUES('2011-01-01'),('2011-01-01'),('2011-01-01'),('2011-01-01')

SQL:

SELECT  DATEADD(YY,
        LU.[ROW] * (-1),A.CURRENT_YEAR) [YEAR],LU.CURRENT_YEAR [Static_YEAR]
FROM    @TAB1 A,
        (SELECT *,(ROW_NUMBER() OVER (ORDER BY CURRENT_YEAR)) - 1 [ROW] FROM @TAB2) LU

<强>结果

enter image description here

答案 2 :(得分:0)

这适用于您的情况:

SELECT *
FROM (SELECT Current_Year
      FROM TableName) AS Current_Year
, (SELECT Start_Date
   FROM TableName) AS Start_Date

当您具有在联接右侧返回标量值的函数时,将使用“交叉应用”。