我有两个表,我想要联合并按日期排序,我需要一个结果中的值,我可以将记录分组报告 - 在这种情况下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
列中的值更新,以便tbl1中日期值之间的tbl2记录具有来自tbl1的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 :(得分: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
但实际上,您的数据结构需要整理(这是上述查询尝试的大部分内容)