27,579
社区成员
发帖
与我相关
我的任务
分享
with a as (
select 1 as id,N'张三' as name union all
select 2,N'李四' union all
select 3,N'王五'
),b as (
select 1 as id,1 as nid,200 as money union all
select 2,1,300 union all
select 3,3,100 union all
select 4,3,500 union all
select 5,3,200
)
select a.name, SUM(isnull(b.money,0)) money from a left join b
on a.id = b.nid
group by a.id, a.name
with a as (
select 1 as id,N'张三' as name union all
select 2,N'李四' union all
select 3,N'王五'
),b as (
select 1 as id,1 as nid,200 as money union all
select 2,1,300 union all
select 3,3,100 union all
select 4,3,500 union all
select 5,3,200
)
select * from a
cross apply(
select isnull(sum(money),0) as total,count(0) as 次数,isnull(avg(money),0) as 平均消费 from b where nid=a.id
) b
--测试数据
if not object_id(N'Tempdb..#TableA') is null
drop table #TableA
Go
Create table #TableA([Id] int,[Name] nvarchar(22))
Insert #TableA
select 1,N'张三' union all
select 2,N'李四' union all
select 3,N'王五'
GO
if not object_id(N'Tempdb..#TableB') is null
drop table #TableB
Go
Create table #TableB([Id] int,[Nid] int,[Money] int)
Insert #TableB
select 1,1,200 union all
select 2,1,300 union all
select 3,3,100 union all
select 4,3,500 union all
select 5,3,200
Go
--测试数据结束
SELECT #TableA.Id,
Name,
ISNULL(SUM(Money),0) AS Total
FROM #TableA
LEFT JOIN #TableB
ON #TableB.Nid = #TableA.Id
GROUP BY #TableA.Id,
Name
ORDER BY #TableA.Id
-- 使用子查询
select A.ID, A.NAME, (select SUM(b.Money) from B where A.ID = B.NID) Total
from A