SQL两表联合查询,并排重
有两个表 A表字段 gid,goodsno,pro B表字段 gid,pro,dw 两表之间有重复数据,并且有些数据A表有,B表无,有些数据B表有A表无,要求联合查询,两表间重复数据的只保留一条,并且显示A B表的数据,有谁能帮忙吗?
gid goodsno pro
1 bb dan
2 cc xie
3 dd wan
4 ee ws
5 vv sa
gid pro dw
1 dan s
2 xie s
6 xiao s
结果:
gid goodsno pro
1 bb dan
2 cc xie
3 dd wan
4 ee ws
5 vv sa
6 xiao s
[解决办法]
----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-12-30 09:30:25
-- Version:
-- Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64)
--Dec 28 2012 20:23:12
--Copyright (c) Microsoft Corporation
--Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
--
----------------------------------------------------------------
--> 测试数据:[A]
if object_id('[A]') is not null drop table [A]
go
create table [A]([gid] int,[goodsno] varchar(2),[intercode] int,[pro] varchar(3))
insert [A]
select 1,'bb',555,'dan' union all
select 2,'cc',666,'xie' union all
select 3,'dd',777,'wan' union all
select 4,'ee',888,'ws' union all
select 5,'vv',999,'sa'
if object_id('[B]') is not null drop table [B]
go
create table [B]([gid] int,[pro] varchar(4),[intercode] int,[dw] varchar(1))
insert [B]
select 1,'dan',555,'s' union all
select 2,'xie',666,'s' union all
select 6,'xiao',222,'s'
--------------开始查询--------------------------
SELECT gid,MAX(goodsno)goodsno,MAX(intercode)intercode,MAX(pro)pro
FROM (
select * from [A]
UNION ALL
select gid,NULL [goodsno],intercode,pro
from [B]
)a
GROUP BY gid
----------------结果----------------------------
/*
gid goodsno intercode pro
----------- ------- ----------- ----
1 bb 555 dan
2 cc 666 xie
3 dd 777 wan
4 ee 888 ws
5 vv 999 sa
6 NULL 222 xiao
*/