SQL 连表查询
本帖最后由 lala133 于 2013-01-11 15:21:54 编辑 有两个表,分别是a,b,数据如下
a
id tm sp kc cy danh
1 02 2 null null aa
2 01 3 null null aa
3 03 2 null null aa
4 05 4 null null bb
5 10 3 null null cc
b
id tm sp kc cy danh
1 02 null 1 null aa
2 01 null 2 null aa
3 10 null 3 null dd
我要的结果是
tm sp kc cy danh
02 2 1 1 aa
01 3 2 1 aa
03 2 0 2 aa
cy=sp-kc,tm是主键,tm、danh是唯一的。
现在选的danh是aa
其实就是,如果表a和表b中,条码一样的就合并成一条,a有b没有或b有a没有的也显示,但是null要变成0, sql
[解决办法]
select 字段 from a with(nolock)
union
select 字段 from b with(nolock)
Null——>0
case when 字段 is null then 0 end
[解决办法]
-->生成表a
if object_id('a') is not null
drop table a
Go
Create table a([id] smallint,[tm] nvarchar(2),[sp] smallint,[kc] nvarchar(50),[cy] nvarchar(50),[danh] nvarchar(2))
Insert into a
Select 1,N'02',2,null,null,N'aa'
Union all Select 2,N'01',3,null,null,N'aa'
Union all Select 3,N'03',2,null,null,N'aa'
Union all Select 4,N'05',4,null,null,N'bb'
Union all Select 5,N'10',3,null,null,N'cc'
-->生成表b
if object_id('b') is not null
drop table b
Go
Create table b([id] smallint,[tm] nvarchar(2),[sp] nvarchar(50),[kc] smallint,[cy] nvarchar(50),[danh] nvarchar(2))
Insert into b
Select 1,N'02',null,1,null,N'aa'
Union all Select 2,N'01',null,2,null,N'aa'
Union all Select 3,N'10',null,3,null,N'dd'
select
ISNULL(a.tm,b.tm)AS id
,COALESCE(a.sp,b.sp,0)AS sp
,COALESCE(a.kc,b.kc,0)AS kc
,COALESCE(a.sp,b.sp,0)-COALESCE(a.kc,b.kc,0)AS cy
,ISNULL(a.danh,b.danh)AS danh
from a
FULL JOIN b ON a.tm=b.tm AND a.danh=b.danh
WHERE ISNULL(a.danh,b.danh)='aa'
/*
id sp kc cy danh
---- ----------- ----------- ----------- ----
02 2 1 1 aa
01 3 2 1 aa
03 2 0 2 aa
*/
Go