我有两个表Tab1(id,time),Tab2(id,time)
这两个表id一对一关系
-----------------------------------
我想创建一个临时表Tab(id,time),通过上面上个表连接,把数据插入Tab,
但是插入time必须是最大的那行数据
-------------------------------------
我举个例子吧
Tab1(id,time)
    (1 , '2010-07-01')
    (2 , '2011-01-02')
Tab2(id,time)
    (1,'2010-07-02')
    (2,'2011-01-01')
所以我得到临时表#Tab的数据是(1,'2010-07-02'),(2, '2011-01-02')
-------------------------------
请问我sql要怎么写

解决方案 »

  1.   

    select ID,max([time]) as [time]
    into #Tab
    from (select ID,[time] from tab1
    uinon all
    select ID,[time] from tab2
    )t
    group by ID
      

  2.   


    select * into #Tab from Tab1update a set [time]=b.[time]
    from #Tab a join Tab2 b on (a.id=b.id)
    where [time]<b.[time]
      

  3.   

    Tab1和Tab2如果都很大的话,union估计效率不高,纯猜测未实践,所以建议分2步
      

  4.   

    打錯一個字母select ID,max([time]) as [time] into #Tab 
    from (select ID,[time] from tab1 union all select ID,[time] from tab2 )t group by ID
      

  5.   

    ;with f as
    (
    select ID,[time] from tab1 union all select ID,[time] from tab2 
    )
    select * from f t where time=(select max(time) from f where id=t.id)
      

  6.   

    呵呵,谢谢上面各位。
    不过都有用了union,这个前提我两个表的字段名都为id吧,
    但是如果两个表关联的字段名不一样呢,union就不能用了吧?