22,298
社区成员
发帖
与我相关
我的任务
分享--测试数据
if not object_id(N'Tempdb..#部门表') is null
drop table #部门表
Go
Create table #部门表([dep] nvarchar(21))
Insert #部门表
select N'A' union all
select N'B' union all
select N'C' union all
select N'D' union all
select N'E'
GO
if not object_id(N'Tempdb..#数据表') is null
drop table #数据表
Go
Create table #数据表([dep] nvarchar(21),[num] int)
Insert #数据表
select N'A',30 union all
select N'C',40
Go
--测试数据结束
SELECT
#部门表.dep,
ISNULL(num, 0) AS num
FROM
#部门表
LEFT JOIN
#数据表
ON #数据表.dep = #部门表.dep;

select a.部门名称,isnull(b.值,0) from 部门表 as a
left join 数据表 as b on a.部门名称=b.部门名称
右连接,然后isnull函数搞定