首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

SQL 合并两表,来帮忙看下,先感谢

2012-05-27 
SQL 合并两表,高手进来帮忙看下,先感谢表1编号数量地址产品----------------------------------------1112

SQL 合并两表,高手进来帮忙看下,先感谢
表1
编号 数量 地址 产品
----------------------------------------
111206006  
111206006  
111206006
111206006
111206006
111206006
111207022
111207022
111207022
111207022
111207022
表2
编号 数量 地址 产品
111206006 3 345 ps01
111206006 6 345 ps02
111206006 7 353 ps01
111207022 7 333 ps01
111207022 7 323 ps01
111207024 2 333 ps01
111207024 6 323 ps03
111207024 9 333 ps06
111207024 21 323 ps09

结果
编号 数量 地址 产品
111206006 3 345 ps01
111206006 6 345 ps02
111206006 7 353 ps01
111206006
111206006
111206006
111207022 7 333 ps01
111207022 7 323 ps01
111207022
111207022
111207022
需求,把表2相对应的记录更新到表1中,同时表1记录行数不变,得出结果如最后一个表,

[解决办法]
LFET JOIN.
[解决办法]

SQL code
create table 表1(编号 varchar(15), 数量 varchar(5), 地址 varchar(5), 产品 varchar(6))insert into 表1(编号)select '111206006' union allselect '111206006' union allselect '111206006' union allselect '111206006' union allselect '111206006' union allselect '111206006' union allselect '111207022' union allselect '111207022' union allselect '111207022' union allselect '111207022' union allselect '111207022'create table 表2(编号 varchar(15), 数量 varchar(5), 地址 varchar(5), 产品 varchar(6))insert into 表2select '111206006', '3', '345', 'ps01' union allselect '111206006', '6', '345', 'ps02' union allselect '111206006', '7', '353', 'ps01' union allselect '111207022', '7', '333', 'ps01' union allselect '111207022', '7', '323', 'ps01' union allselect '111207024', '2', '333', 'ps01' union allselect '111207024', '6', '323', 'ps03' union allselect '111207024', '9', '333', 'ps06' union allselect '111207024', '21', '323', 'ps09'update t1set t1.数量=isnull(t2.数量,''),    t1.地址=isnull(t2.地址,''),    t1.产品=isnull(t2.产品,'')from (select row_number() over(partition by 编号 order by getdate()) rn, 编号,数量,地址,产品 from 表1) t1left join (select row_number() over(partition by 编号 order by getdate()) rn, 编号,数量,地址,产品 from 表2) t2 on t1.编号=t2.编号 and t1.rn=t2.rnselect * from 表1/*编号              数量    地址    产品--------------- ----- ----- ------111206006       3     345   ps01111206006       6     345   ps02111206006       7     353   ps01111206006                   111206006                   111206006                   111207022       7     333   ps01111207022       7     323   ps01111207022                   111207022                   111207022                   (11 row(s) affected)*/ 

热点排行
Bad Request.