2013-08-20 30 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