我正在使用SQL Server 2012并正在编写一份报告,要求我查找两个日期之间的天数差异。
基本上,对于特定的ReportID
,我试图找出ReportCompletedDate
时ReportType = 'PaperReceived'
- (ReportCompletedDate
之间的天数差异ReportType = 'Form Completed'
)
我试着在下面给出一些记录......
ReportID ReportType ReportCompletedDate
-------------------------------------------------
450 PaperReceived 9/5/2013
450 Form Completed 8/13/2013
451 PaperReceived 9/7/2013
451 Form Completed 7/12/2013
452 PaperReceived 10/6/2013
452 Form Completed 3/13/2013
因此,对于ReportID = 450
,例如,我想在几天内获得9/5/2013 - 8/13/2013
。
如果有人也知道如何在日历日和工作日这样做,那就太棒了......但至少日历日应该没问题。
我不确定如何解决这个问题,通常在两个日期排成一行时,我更容易理解,但不知道如何在日期到来时如何处理分开的行。任何建议都会很高兴。
答案 0 :(得分:2)
您可以进行自我加入,使其显示在“一行”上。像这样:
SELECT DateDiff(day,BASE.ReportCompleteDate, FORM.ReportCompleteDate) as Diff
FROM TABLE_NAME_YOU_DID_NOT_SAY BASE
LEFT JOIN TABLE_NAME_YOU_DID_NOT_SAY FORM ON BASE.ReportId = FORM.ReportID AND FORM.ReportType = 'Form Completed'
WHERE BASE.ReportType = 'PaperRecieved'
答案 1 :(得分:2)
请在下面找到一种方法......
SELECT RCVD.REPORTID
, DATEDIFF(DAY, RCVD.REPORTCOMPLETEDDATE, CMPLD.REPORTCOMPLETEDDATE) DAY_DIFF
FROM (
SELECT REPORTID
, REPORTCOMPLETEDDATE
FROM REPORTS
WHERE REPORTTYPE = 'PaperReceived'
) RCVD
JOIN (
SELECT REPORTID
, REPORTCOMPLETEDDATE
FROM REPORTS
WHERE REPORTTYPE = 'Form Completed'
) CMPLD
ON RCVD.REPORTID = CMPLD.REPORTID