我需要查看给定时间范围内的每个月/每年,并检查在该月份和年份中文件是否处于打开状态。在每个文件上都有一个开放日期和结束日期,以便我想检查每个文件是否开放日期的月份和年份小于或等于该范围中的每个月份/年份,然后如果结束日期为空或有一个月/一年大于该范围内的每月/年。然而,我很难说如何通知查询当前的月份是什么,我正在看。我的查询如下所示:SQL检查文件在特定时间段内是否处于打开状态
-- New Files
select distinct datepart(MM, ws.CaseOpenDate) as 'Month',
datepart(yyyy, ws.CaseOpenDate) as 'Year',
count(ws.WorksheetID) as 'Count'
into #newfiles
from LGSIntersect lgs
join Worksheet ws on ws.LGSIntersectID = lgs.LGSIntersectID
where ws.CaseOpenDate between '01/01/2016' and '03/01/2017'
and lgs.GroupCodeID = '307'
group by datepart(MM, ws.CaseOpenDate), datepart(yyyy, ws.CaseOpenDate)
-- Open Files
select distinct datepart(MM, ws.CaseOpenDate) as 'Month',
datepart(yyyy, ws.CaseOpenDate) as 'Year',
datepart(MM, ws.CloseDate) as 'CloseMonth',
datepart(yyyy, ws.CloseDate) as 'CloseYear',
count(ws.WorksheetID) as 'Count'
into #openfiles
from LGSIntersect lgs
join Worksheet ws on ws.LGSIntersectID = lgs.LGSIntersectID
where ws.CaseOpenDate <= '03/01/2017'
and (ws.CloseDate is null or ws.CloseDate >= '01/01/2016')
and lgs.GroupCodeID = '307'
group by datepart(MM, ws.CaseOpenDate), datepart(yyyy, ws.CaseOpenDate),
datepart(MM, ws.CloseDate), datepart(yyyy, ws.CloseDate)
-- New Investigations
select distinct datepart(MM, ws.InvestigationDate) as 'Month',
datepart(yyyy, ws.InvestigationDate) as 'Year',
count(ws.WorksheetID) as 'Count'
into #newinv
from LGSIntersect lgs
join Worksheet ws on ws.LGSIntersectID = lgs.LGSIntersectID
where ws.InvestigationDate between '01/01/2016' and '03/01/2017'
and lgs.GroupCodeID = '307'
group by datepart(MM, ws.InvestigationDate),
datepart(yyyy, ws.InvestigationDate)
-- Ques Sent
select distinct
datepart(MM, qpd.PrintDate) as 'Month',
datepart(yyyy, qpd.PrintDate) as 'Year',
count(qpd.QuestionnairePrintDetailID) as 'Count'
into #ques
from LGSIntersect lgs
join QuestionnairePrintDetail qpd
on qpd.LGSIntersectID = lgs.LGSIntersectID
where qpd.PrintDate between '01/01/2016' and '03/01/2017'
and lgs.GroupCodeID = '307'
group by datepart(MM, qpd.PrintDate),
datepart(yyyy, qpd.PrintDate)
select distinct
nf.Month,
nf.Year,
isnull(sum(q.Count), 0) as '# of Ques Sent',
isnull(sum(ni.Count), 0) as '# of New Investigations',
isnull(sum(nf.Count), 0) as '# of New Files',
isnull(sum(opf.Count), 0) as '# of Open Files'
from #newfiles nf
left join #ques q on q.Month = nf.Month and q.Year = nf.Year
left join #newinv ni on ni.Month = nf.Month and ni.Year = nf.Year
left join #openfiles opf on (opf.Month + opf.Year <= nf.Month + nf.Year)
and (opf.CloseMonth is null
or (opf.CloseMonth + opf.CloseYear > nf.Month + nf.Year))
group by nf.Month, nf.Year
现在没有办法,以确保它是唯一有问题每个月/年期间被打开的文件总数(总结不像“发送疑问句的#”和“#的新文件“,当我删除打开文件的逻辑时,它们可以正确计算)。任何提示将不胜感激 - 让我知道如果我需要提供额外的信息。我正在休6个月的病假,所以我很生气。谢谢!
我正在使用MS SQL服务器 – Jana