SQL两个表字段相加并排序

2024-11-24 16:41:36
推荐回答(5个)
回答1:

select data_all.产品名,
case when tab1.咨询数 is null then 0 else tab1.咨询数 end +
case when tab2.订单亏渣盯数 is null then 0 else tab2.订单数 end 总数,
case when tab2.订单数 is null then 0 else tab2.订单数 end 总数
case when tab1.咨询数 is null then 0 else tab1.咨询数 end 咨询数

from
(select 产品名 from 表1
union
select 产品名 from 表2
) data_all
left outer join 表1 tab1 on data_all.产品名=tab1.产品名
left outer join 表2 tab2 on data_all.产品名=tab2.产品销和名

order by
case when tab1.咨询数 is null then 0 else tab1.咨询数 end +
case when tab2.订单数梁哗 is null then 0 else tab2.订单数 end

回答2:

select case when T1.产品名 is null then T2.产品名 else T1.产品名 end as
"产品名", sum(nvl(T1.咨询数,0))+sum(nvl(T2.订单数陵返,0)) as "总数",sum
(nvl(T2.订单数,0)) as "总订单数",sum(nvl(T1.咨询数,0)) as "总咨询数"
from 表1 T1 full join 表二 T2
on(T1.产品名雀姿=T2.产品名)
group by case when T1.产品名 is null then T2.产品名 else T1.产品名 end
order by 总顷汪绝数

回答3:

可以用union all再group by 操作,如:
select
产滑悄品名,sum(总数),sum(订单数),sum(咨询数)
(
select 产品名,咨询数 总数,咨询数, 0 订单数 from 表1
union all

select 产品衫此名,订单数 总数,0 咨询数, 订信塌渣单数 from 表2

) group by 产品名,order by sum(总数)

回答4:

select
产品名,
总数=订单数+咨询数,
订单数,
咨询数
from
(
select 产品名,sum(订单数) as 订单数举物,sum(咨询数) as 咨询数
from
(
select 产品名,订单氏答尘数,'' as 咨询数 from 表2
union
select 产品名,'' as 订单数,咨询数 from 表1
) a
group by 产品名歼禅
) b

回答5:

create table #a (id int,name char(10),num int )
insert #a select 1 ,'产品模袭1'李败, 20
insert #a select 2, '产品2', 15
create table #b (id int,name char(10),num int )
insert #b select 1 ,'产品旦扰兄3', 55
insert #b select 2, '产品2', 30

select identity(int,1,1) as id , t1.name,t1.num,t1.anum , isnull (t2.num,0) as bnum
into #c
from
(select t1.*, isnull (t2.num,0) as anum
from
(select * from (select * from #A
union all
select * from #b) t
where t.name not in
(select t1.name from #a t1,#b t2 where t1.name=t2.name)
union all
select t1.id, t1.name ,(t1.num+t2.num) as num from #a t1,#b t2 where t1.name=t2.name ) t1 left outer join #a t2
on t1.name=t2.name) t1 left outer join #b t2
on t1.name=t2.name
order by t1.name

select * from #c