Hi @J Like MIB
There are two reasons why you got nothing from the Output:
First, there are some simple mistakes in your JOIN conditions that may be typos. For example, and p1.PrjId1 = p2.PrjId2
should be and p1.PrjId2 = p2.PrjId2
By the way, the sample data you provided needs to be slightly modified. Check this:
create table projects (PrjId1 varchar(6), PrjId2 varchar(6), prjSchDate DATE);
Insert into projects (PrjId1, PrjId2, prjSchDate) values
('Prj022','000001', '2022-01-02'),
('Prj022','000002', '2022-04-01')
GO
Second, since you JOIN prjProcess as p3 ,while you only select p2.prjProcessDesc, p2.prjProcessStatus
.You can't see the columns in the p3 table if you don't select p3.prjProcessDesc, p3.prjProcessStatus
To get the results you want, please check this query:
;WITH CTE AS
(
SELECT P2.*,ROW_NUMBER()OVER(PARTITION BY P2.PrjId1,P2.PrjId2,prjProcessDesc ORDER BY prjProcessRecDate DESC)AS RNum
FROM #projects P1 JOIN #prjProcess P2 ON P1.PrjId1=P2.PrjId1 AND P1.PrjId2=P2.PrjId2
)
SELECT A.PrjId1,A.PrjId2,A.prjProcessDesc,A.prjProcessStatus,A.prjProcessRecDate
,B.prjProcessStatus,B.prjProcessRecDate,DATEDIFF(DAY,A.prjProcessRecDate,B.prjProcessRecDate)AS NumberOfDays
FROM (SELECT * FROM CTE WHERE prjProcessStatus='Accepted')A
JOIN (SELECT * FROM CTE WHERE RNum=1)B ON A.PrjId1=B.PrjId1 AND A.PrjId2=B.PrjId2 AND A.prjProcessDesc=B.prjProcessDesc
Output:
Best regards,
LiHong
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.