【问题标题】:update records in a union select query更新联合选择查询中的记录
【发布时间】:2013-08-22 06:31:09
【问题描述】:

我有两个表,其中包含要合并并按日期排序的事件,我需要一个结果值,我可以将记录分组以进行报告 - 在本例中为 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 可以做到这一点,还是我需要不同的方法?

【问题讨论】:

  • 请添加您正在使用的数据库正在询问 sql 问题,oracle/postgess/mysql/mssql 之间存在很多差异 ...
  • 根据语法标记为 MS SQL Server

标签: sql sql-server sql-server-2012


【解决方案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

但实际上,您的数据结构需要整理(这是上述大部分查询尝试做的事情)

【讨论】:

  • 它似乎应该可以工作,但它没有在 sqlfiddle (sqlfiddle.com/#!6/0e554/18) 中给出所需的结果。 [必须删除哈希,因为它抛出了一些错误]
  • @Raze2dust 在小提琴中为我工作!
  • @podiluska 谢谢,为我工作。同意数据结构需要整理以使其更容易。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多