使用临时表,先查询出结果,在用于后面表的子查询或者联查
-- 删除表1if EXISTS ( SELECT 1 FROM tempdb.sys.objects where name like '#temp_PublishRecord%' ) beginDROP TABLE #temp_PublishRecordprint '已删除临时表 #temp_PublishRecord'end--创建临时表 1
SELECT
[ArticleId],k.[FirstAuthorDeptId]
,[PublishChannel]into #temp_PublishRecord --创建临时表FROM [PublishRecord] as pleft join [Article] as k on k.id=p.ArticleId where -- k.[FirstAuthorDeptId]=m.[FirstAuthorDeptId] k.SendTime >= '2024-05-01' AND k.SendTime < '2025-01-01' and k.ArticleStatus!=1700 and k.ArticleStatus!=1600and k.VStatistic=1-- 删除表2if EXISTS ( SELECT 1 FROM tempdb.sys.objects where name like '#temp_AdoptedRecord%' ) beginDROP TABLE #temp_AdoptedRecordprint '已删除临时表 #temp_AdoptedRecord'end--创建临时表 2
SELECT [ArticleId],[Operatortime],[Channel_name],a.[FirstAuthorDeptId]into #temp_AdoptedRecordFROM [AdoptedRecord] as bleft join Article as a on a.Id=b.ArticleId where -- a.[FirstAuthorDeptId]='0443fea5641a453780e2e2780f2ff5b3'a.VStatistic=1 and a.ArticleStatus!=1700 and a.ArticleStatus!=1600and b.Operatortime> '2024-05-01' AND b.Operatortime < '2025-01-01'select m.*,
-- 发布量 ( SELECT count(distinct [ArticleId] ) FROM #temp_PublishRecord where [FirstAuthorDeptId]=m.[FirstAuthorDeptId]) as publishNum-- 头条新闻,数量
,( SELECT count(distinct [ArticleId] ) FROM #temp_PublishRecord where [FirstAuthorDeptId]=m.[FirstAuthorDeptId] and [PublishChannel] like '头条新闻%') as ttxwNum-- 重点关注,数量
,( SELECT count(distinct [ArticleId] ) FROM #temp_PublishRecord where [FirstAuthorDeptId]=m.[FirstAuthorDeptId] and [PublishChannel] like '重点关注%') as zdgzNum-- 动态信息,数量
,( SELECT count(distinct [ArticleId] ) FROM #temp_PublishRecord where [FirstAuthorDeptId]=m.[FirstAuthorDeptId] and [PublishChannel] like '动态信息%') as zdgzNum--测试栏目3 采纳数
,(select count([ArticleId]) from #temp_AdoptedRecord
where [FirstAuthorDeptId]=m.[FirstAuthorDeptId] and [Channel_name]='测试栏目3'
) as jtCount
--测试栏目2,采纳数
,(select count([ArticleId]) from #temp_AdoptedRecord
where [FirstAuthorDeptId]=m.[FirstAuthorDeptId] and [Channel_name]='测试栏目2'
) as fgsdtxwCount
--测试栏目1,采纳数
,(select count([ArticleId]) from #temp_AdoptedRecord
where [FirstAuthorDeptId]=m.[FirstAuthorDeptId] and [Channel_name]='测试栏目1'
) as fgsjrywCountfrom (
SELECT a.[FirstAuthorDeptId],d.OrganizationName,count(a.id ) as ReportCount --报送量
FROM [Article] as a
left join Organization as d on d.Id=a.[FirstAuthorDeptId]
where a.VStatistic=1 and a.ArticleStatus!=1700 and a.ArticleStatus!=1600
and a.[FirstAuthorDeptId] is not null
and a.SendTime >= '2024-05-01' AND a.SendTime < '2025-01-01'
group by a.[FirstAuthorDeptId] ,d.OrganizationName
) as m