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

关于SQL 中 UNION 去重复.解决办法

2012-04-28 
关于SQL 中 UNION 去重复...现在想要实现下面效果,不知道如何实现纠结了很久.....Table1表如下:postIdsup_

关于SQL 中 UNION 去重复...
现在想要实现下面效果,不知道如何实现纠结了很久.....
Table1表如下:
  postId sup_id realName postType
  1 12 Tr 1  
  2 13 jk 1
  3 14 pl 1

Table2表如下:
  postId sup_id realName postType
  1 12 Tr 2  
  2 13 gk 2
  3 14 hj 2

怎么样通过union把两表的结果链接起来然后实现下面的结果 

  postId sup_id realName postType
  1 12 Tr 2  
  2 13 jk 1
  3 14 pl 1
  2 13 gk 2
  3 14 hj 2




[解决办法]

SQL code
if object_id('[Table1]') is not null drop table [Table1]gocreate table [Table1] (postId int,sup_id int,realName nvarchar(4),postType int)insert into [Table1]select 1,12,'Tr',1 union allselect 2,13,'jk',1 union allselect 3,14,'pl',1if object_id('[Table2]') is not null drop table [Table2]gocreate table [Table2] (postId int,sup_id int,realName nvarchar(4),postType int)insert into [Table2]select 1,12,'Tr',2 union allselect 2,13,'gk',2 union allselect 3,14,'hj',2select * from [Table1]select * from [Table2]select postid,sup_id,realname,MAX(posttype)from (select postid,sup_id,realname,posttype from Table1 union select postid,sup_id,realname,posttype from Table2 ) Tgroup by postid,sup_id,realname/*1    12    Tr    22    13    gk    22    13    jk    13    14    hj    23    14    pl    1*/ 

热点排行
Bad Request.