求大神,递归求和

jasontimmy 2020-01-07 03:36:45
if not object_id(N'#A') is null
drop table #A
if not object_id(N'#B') is null
drop table #B
Go

create Table #A(
id int,
qty int)
insert into #A
select 1,1 union all
select 1,1 union all
select 2,1 union all
select 2,1 union all
select 3,1 union all
select 4,1
go

create table #B(
id int,
subid int)
insert into #B
select 2,3 union all
select 2,4

输出#A表求和结果不含子id
id qty
1 2
2 4
...全文
58 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
唐诗三百首 2020-01-07
  • 打赏
  • 举报
回复

select id=isnull(b.id,a.id),
       qty=sum(a.qty)
 from #A a
 left join #B b on a.id=b.subid
 group by isnull(b.id,a.id)

/*
id          qty
----------- -----------
1           2
2           4

(2 rows affected)
*/
顺势而为1 2020-01-07
  • 打赏
  • 举报
回复


Select a.id,sum(a.qty) as qty
From #A a
    Left Join #B b on a.id=b.id
Where a.id not in (Select subid From #B)
Group By a.id

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧