2017-06-15 102 views
2

我需要幫助更新日曆表。我有2個表的一個交易表(表T)和一個日曆表(表C)。我試圖更新日曆表中的應用程序ID(app_id)和emp_Id,一旦日期可用,如果日期重疊,則不應更新。更新運行如SQL Server重疊日期

表筆

app_id emp_id stdate  eddate  priority 
-----------------------------------------------  
1  15  2015-01-03 2015-01-05 1 
2  18  2015-01-04 2015-01-06 2 

表C

dates  app_id empid 
---------------------------- 
2015-01-03  null null 
2015-01-04  null null 
2015-01-05  null null 

後的結果應該是

表C

dates  app_id empid 
---------------------------- 
2015-01-03  1  15 
2015-01-04  1  15 
2015-01-05  1  15 
+0

假定日期表T不能重疊,這是上'簡單加入C.dates> = T.stdate AND C.dates <= T.eddate' – ZLK

+0

你需要'app_id'和'emp_id'嗎?他們都是桌T的PK嗎?或者只是前者?我猜'2015-01-06'會有'2 18',對嗎? – Andrew

+0

是的,我需要app_id和emp_id,他們是表中的pk T – user1446930

回答

0

我寫了這關某個東西的上放 我的頭,我希望它爲你的作品:

UPDATE TC 
SET app_id = (SELECT TOP 1 app_id FROM TABLE_T TT WHERE TC.dates BETWEEN TT.stdate AND tt.eddate ORDER BY TT.priority ASC), 
empid = (SELECT TOP 1 emp_id FROM TABLE_T TT WHERE TC.dates BETWEEN TT.stdate AND tt.eddate ORDER BY TT.priority ASC) 
FROM TABLE_C TC 

可以調試此第一與此查詢:

SELECT TC.*, 
new_app_id = (SELECT TOP 1 app_id FROM TABLE_T TT WHERE TC.dates BETWEEN TT.stdate AND tt.eddate ORDER BY TT.priority ASC), 
new_empid = (SELECT TOP 1 emp_id FROM TABLE_T TT WHERE TC.dates BETWEEN TT.stdate AND tt.eddate ORDER BY TT.priority ASC) 
FROM TABLE_C TC 

我用emp_idempid在你的榜樣。

1

我會傾斜apply做到這一點:

update c 
    set app_id = t.app_id, 
     empid = t.empid 
    from table_c c apply 
     (select top 1 t.* 
      from table_t t 
      where tc.dates >= t.stdate and 
       tc.dates <= t.eddate 
      order by t.priority 
     ) t;