34,576
社区成员
发帖
与我相关
我的任务
分享
declare @tableA table (Id int,food varchar(4))
insert into @tableA
select 1,'苹果' union all
select 2,'苹果' union all
select 3,'西瓜'
declare @tableC table (foodId int,foodName varchar(4))
insert into @tableC
select 1,'苹果' union all
select 2,'西瓜' union all
select 3,'香蕉'
select foodName,
(select count(1) from @tableA where food=c.foodName) as 数量 from @tableC c
/*
foodName 数量
-------- -----------
苹果 2
西瓜 1
香蕉 0
*/
select
a.foodname,isnull(b.num,0)
from
tableC as a
left join
(select food ,count(1) as num from tablea group by food)b
on
a.foodName=b.food