管志鹏的计算机主页

C# ASP.NET Java J2EE SSH SQL Server Oracle
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

合并两个表查询结果

Posted on 2011-07-08 16:08  管志鹏  阅读(777)  评论(0编辑  收藏  举报

1.两个不同的表,现在要查询这两个表中的Id,并合并查询结果:(去年重复列)

select brandId   from acc_brand union  select  categoryId from ACC_category

 

 

2.两个不同的表,现在要查询这两个表中的Id,并合并查询结果(保留重复列):

select brandId   from acc_brand union all  select  categoryId from ACC_category

 

3.两个不同的表,现在要查询这两个表中的Id,并合并查询结果,结果中要显示出值是哪个表的:

select 'acc' as tablename, brandId   from acc_brand union  select 'cate' ,categoryId from ACC_category

 

4.两个不同的表,现在要查询这两个表中的Id,并合并查询结果, 查询结果去年Id重复的值 :

select * from (select *,row_number() over(partition by brandId order by brandId) as rowIndex  from 
(select 'acc' as tablename, brandId   from acc_brand union  select 'cate' ,categoryId from ACC_category) as result) as a
where a.rowindex=1

 

注:row_number() over(partition by 列名 order by 列名) 对分组结果进行排序