SQL Server: difference in days for two dates in separate rows

不想你离开。 提交于 2019-12-11 02:37:35

问题


I am using SQL Server 2012 and working an a report currently that is asking me to find the difference in days between two dates.

Basically, for a particular ReportID, I'm trying to find the difference in days between the (ReportCompletedDate when the ReportType = 'PaperReceived') - (ReportCompletedDate when the ReportType = 'Form Completed')

I tried to give some records below...

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

So, for ReportID = 450 for example, I want to get 9/5/2013 - 8/13/2013 in days.

If anyone also knows how to do this for calendar days and business days, that would be awesome...but at least calendar days should be fine.

I'm not sure how to go about this, usually when the two dates are in line, it's easier for me to figure out, but not sure how to go about it when the dates are in separate rows. Any advice would be gladly appreciated.


回答1:


You can do a self join to make it appear on "one line". Like this:

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'



回答2:


Please find below one of the approach...

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


来源:https://stackoverflow.com/questions/42986643/sql-server-difference-in-days-for-two-dates-in-separate-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!