sql统计两张表的和按大小排序

tian79697986 2010-11-22 02:07:02
表1
id ,name,total
1, 张三, 10
2, 李四, 15
3, 王 30

表二

id, cid,name, total1
1, 1, 张三, 10
2, 1, 张三, 12
3, 2, 李四, 10
4, 3, 王, 15
5, 3, 王, 10
6, 3, 王, 10

现想显示结果如下

王 65

张三 32

李 25

...全文
78 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
coleling 2010-11-22
  • 打赏
  • 举报
回复

--借用#1的演示数据

select a.name, total = a.total+b.total
from #ta a join (select cid, total=sum(total1) from #tb group by cid) b on a.id = b.cid

name total
---- -----------
张三 32
李四 25
王 65

(3 行受影响)
华夏小卒 2010-11-22
  • 打赏
  • 举报
回复
--> 测试数据: #ta
if object_id('tempdb.dbo.#ta') is not null drop table #ta
go
create table #ta (id int,name varchar(4),total int)
insert into #ta
select 1,'张三',10 union all
select 2,'李四',15 union all
select 3,'王',30
--> 测试数据: #tb
if object_id('tempdb.dbo.#tb') is not null drop table #tb
go
create table #tb (id int,cid int,name varchar(4),total1 int)
insert into #tb
select 1,1,'张三',10 union all
select 2,1,'张三',12 union all
select 3,2,'李四',10 union all
select 4,3,'王',15 union all
select 5,3,'王',10 union all
select 6,3,'王',10

select name,total=sum(total)
from
(
select * from #ta
union all
select cid,name,total1 from #tb
)t
group by name
order by total desc

name total
---- -----------
王 65
张三 32
李四 25

(3 行受影响)

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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