34,590
社区成员
发帖
与我相关
我的任务
分享
select ..
from (
select *
from tbA
where 出库用途 is not null
and yourcondition
union
select *
from tbB
where 1=1
and yourcondition
) as a
group by ..
修正一下select ..
from (
select *
from tbA
where 出库用途 is not null
and yourcondition
union
select *
from tbB
and yourcondition
) as a
group by ..
create table tmptb (材料名称 varchar(10),出库数量 int,出库用途 varchar(10),金额 int)
insert tmptb
select '材料一',80,'检验',80 union all
select '材料二',200,'办公',200 union all
select '材料三',900,null,900 union all
select '材料四',230,'机台一',230
create table tmptb2 (材料名称 varchar(10),出库数量 int,出库用途 varchar(10),金额 int)
insert tmptb2
select '材料三',100,'机台二',100 union all
select '材料三',200,'机台三',200 union all
select '材料三',500,'机台四',500 union all
select '材料三',100,'机台五',100
select *
from tmptb
select *
from tmptb2
select *
from tmptb a left join tmptb2 b on (a.材料名称=b.材料名称)
材料名称 出库数量 出库用途 金额
---------- ----------- ---------- -----------
材料一 80 检验 80
材料二 200 办公 200
材料三 900 NULL 900
材料四 230 机台一 230
(所影响的行数为 4 行)
材料名称 出库数量 出库用途 金额
---------- ----------- ---------- -----------
材料三 100 机台二 100
材料三 200 机台三 200
材料三 500 机台四 500
材料三 100 机台五 100
(所影响的行数为 4 行)
材料名称 出库数量 出库用途 金额 材料名称 出库数量 出库用途 金额
---------- ----------- ---------- ----------- ---------- ----------- ---------- -----------
材料一 80 检验 80 NULL NULL NULL NULL
材料二 200 办公 200 NULL NULL NULL NULL
材料三 900 NULL 900 材料三 100 机台二 100
材料三 900 NULL 900 材料三 200 机台三 200
材料三 900 NULL 900 材料三 500 机台四 500
材料三 900 NULL 900 材料三 100 机台五 100
材料四 230 机台一 230 NULL NULL NULL NULL
(所影响的行数为 7 行)
--这样取:
select * from 表一 where isnull(出库用途,'')!=''
union all
select a.* from 表二 a,表一 b
where a.材料名称=b.材料名称 and isnull(b.出库用途,'')=''
--上面的是第一次出库的,下面是第二次出库的。
select ..
from (
select *
from tbA
where 出库用途 is not null
union
select *
from tbB
) as a
group by ..