2013-08-20 29 views
1

更新記錄我有兩個表我想要聯盟和按日期排序的事件,我需要一個結果值,我可以分組記錄的報告 - 在這種情況下code2在工會選擇查詢

CREATE TABLE #tbl1 (code1 INT, codeDate DATETIME, code2 INT) 
CREATE TABLE #tbl2 (code1 INT, codeDate DATETIME, code2 INT) 

INSERT INTO #tbl1 VALUES(1, '01 jan 2013 12:00:00', 123) 
INSERT INTO #tbl1 VALUES(2, '01 jan 2013 14:00:00', 123) 
INSERT INTO #tbl1 VALUES(1, '01 jan 2013 15:00:00', 234) 
INSERT INTO #tbl1 VALUES(2, '01 jan 2013 18:00:00', 234) 

INSERT INTO #tbl2 VALUES(10, '01 jan 2013 12:10:00', 0) 
INSERT INTO #tbl2 VALUES(20, '01 jan 2013 13:20:00', 0) 
INSERT INTO #tbl2 VALUES(10, '01 jan 2013 15:10:00', 0) 
INSERT INTO #tbl2 VALUES(20, '01 jan 2013 16:20:00', 0) 

SELECT * FROM #tbl1 UNION SELECT * FROM #tbl2 ORDER BY CODEDATE 

返回

code1 codeDate     code2 
1  2013-01-01 12:00:00.000  123 
10  2013-01-01 12:10:00.000  0 
20  2013-01-01 13:20:00.000  0 
2  2013-01-01 14:00:00.000  123 
1  2013-01-01 15:00:00.000  234 
10  2013-01-01 15:10:00.000  0 
20  2013-01-01 16:20:00.000  0 
2  2013-01-01 18:00:00.000  234 

我還想得到的code2列中的值進行更新,以便在TBL 1日期值之間屬於tbl2的記錄具有從TBL 1的code2值。 (行2,3,6 & 7結果),例如:

code1 codeDate     code2 
1  2013-01-01 12:00:00.000  123 
10  2013-01-01 12:10:00.000  123 
20  2013-01-01 13:20:00.000  123 
2  2013-01-01 14:00:00.000  123 
1  2013-01-01 15:00:00.000  234 
10  2013-01-01 15:10:00.000  234 
20  2013-01-01 16:20:00.000  234 
2  2013-01-01 18:00:00.000  234 

UNION這是可能的,或者我需要一種不同的方法?

+0

請添加您正在使用的數據庫是問SQL問題,oracle/postgess/mysql/mssql之間有很多不同之處...... – Sibster

+0

Microsoft SQL 2012 – Matt

+0

基於語法 –

回答

1

試試這個

update #tbl2 
set code2 = t1.code 
from 
    #tbl2 t2 
     inner join 
    (

     select 
      t1s.codeDate start, 
      t1f.codeDate finish, 
      t1s.code2 code 
     from #tbl1 t1s 
      inner join #tbl1 t1f 
       on t1s.code2 = t1f.code2 
     where t1s.code1=1 
     and t1f.code1 = 2 
    ) t1 
     on t2.codeDate between t1.start and t1.finish 

SELECT * FROM #tbl1 UNION SELECT * FROM #tbl2 ORDER BY CODEDATE 

不過說真的,你的數據結構需要收拾一下(這是上面查詢的大部分試圖做)

+0

+1標記爲MS SQL Server - 爲了很好的答案。 – Devart

+0

它似乎應該可以工作,但它不會在sqlfiddle(http://sqlfiddle.com/#!6/0e554/18)中提供所需的結果。 [必須刪除哈希,因爲它是拋出一些錯誤] –

+0

@ Raze2dust在我的小提琴中工作! – podiluska