【发布时间】:2017-05-19 20:55:45
【问题描述】:
我需要查看给定时间范围内的每个月/年,并检查在该月和该年,文件是否处于打开状态。在每个文件上都有一个打开日期和关闭日期,因此对于每个文件,我想检查打开日期的月份和年份是否小于或等于该范围内的每个月/年,然后关闭日期是否为空或有大于该范围内的每个月/年的月/年。但是,我不知道如何通知查询我正在查看的当前月份年份是什么。我的查询如下所示:
-- 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 服务器
标签: sql sql-server date-range