这样的sql怎么写?

teclogid 2006-06-22 04:59:11
有个主表,比如交易表 trade(id,name),有个流水表 detail(id,trade_id,money)
现在我要用一条sql,查询出trade表id=x中所有字段和流水表里trade_id=x所有的money的总和,请问这样的sql怎么写?
...全文
227 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
liangpei2008 2006-06-22
  • 打赏
  • 举报
回复
declare @trade table(id int,name varchar(10))
insert @trade select 1,'aaa'
union all select 2,'bbb'
union all select 3,'ccc'
--------------------------------------------
declare @detail table(id int,trade_id int,money int)
insert @detail select 1,1,30
union all select 2,1,20
union all select 3,2,20
union all select 3,2,20
--------------------------------------------
--SQL语句
select A.id,A.name,isnull(B.money,0) as money
from @trade A left join
(
select trade_id,sum(money) as money
from @detail
group by trade_id) B
on A.id=B.trade_id
where A.id=1 --条件
liujuns 2006-06-22
  • 打赏
  • 举报
回复
select t1.id,t1.name,sum(t2.money) as sum_money
from trade t1 ,detail t2
where t1.id *= t2.trade_id and t1.id = x
group by t1.id,t1.name
teclogid 2006-06-22
  • 打赏
  • 举报
回复
谢谢,如果我的detail表里没有数据,那记录能显示出来吗?我希望显示出来,总金额是空或是0都可以
itzhiren 2006-06-22
  • 打赏
  • 举报
回复
select t1.id,t1.name,sum(t2.money) as sum_money
from trade t1 ,detail t2
where t1.id = t2.trade_id and t1.id = x
group by t1.id,t1.name
冷箫轻笛 2006-06-22
  • 打赏
  • 举报
回复

select t1.id,t1.name,sum(t2.money) as sum_money
from trade t1 ,detail t2
where t1.id = t2.trade_id and t1.id = x
group by t1.id,t2.name

34,838

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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