2014-06-23 64 views
-1

我有一個表,它將存儲當年的日期,我在該表中也有一個開始日期。是否有可能使用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 
+0

這個「交叉應用」是什麼樣的? – podiluska

+0

但爲什麼它應該使用CROSS APPLY很重要?這個結果也可以通過其他方式實現。 –

回答

2

下面將爲使用CROSS所期望的結果適用於:

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來完成工作,也許會讓語義上更有意義,雖然執行計劃將結束是的相同。

+0

用cte和#temp做這件事很容易,但由於我的項目需求持有批量數據無法做到這一點,我試過#temp和cte但執行時間太高。所以我想要一些可以做到的機制。 – Azar

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

0

這應該工作你的情況:

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

當你有一個函數在你的連接的右邊返回一個標量值的時候,使用交叉應用。