I am trying to produce a report which identifies client cases which were open during each week of a year. Currently I have the following SQL which returns all clients with an indicator on whether their case was open during week 1 of our calendar. A client has two aspects which identifies if their case is open – their MOV_START_DATE and their ESU_START DATE should be greater than end date of the period, and their MOV_END_DATE/ESU_START DATE should be either null or greater than the start date of the period.
The below code works, but I thought I could just copy the left join WK1 and rename it WK2 to return information for week 2 but I’m getting an error relating to ambiguously named columns. Additionally, I’m guessing that having 52 (one for each week) left joins on a report isn’t particularly advisable, so again I’m wondering if there is a better way of achieving this?
SELECT
A.ESU_PER_GRO_ID,
A.ESU_ID,
A.STATUS,
B.MOV_ID,
B.MOV_START_DATE,
B.MOV_END_DATE,
A.ESU_START_DATE,
A.ESU_END_DATE,
LS.CLS_DESC,
nvl2(wk1.PRD_PERIOD_NUM,'Y','N') as "Week1"
FROM
A
LEFT JOIN B ON B.MOV_PER_GRO_ID = A.ESU_PER_GRO_ID
LEFT JOIN LS ON LS.CLS_CODE = A.STATUS
LEFT JOIN O_PERIODS WK1 ON B.MOV_START_DATE < WK1.PRD_END_DATE
AND (B.MOV_END_DATE IS NULL OR B.MOV_END_DATE > WK1.PRD_START_DATE)
AND A.ESU_START_DATE < WK1.PRD_END_DATE
AND (A.ESU_END_DATE IS NULL OR A.ESU_END_DATE > WK1.PRD_START_DATE)
AND PRD_CAL_ID = 'E1190' AND WK1.PRD_PERIOD_NUM = 1 AND WK1.PRD_YEAR = 2012
WHERE
B.MOV_START_DATE Is Not Null
AND A.STATUS <> ('X')
Hopefully I have provided enough information, but if not, I am happy to answer questions. Thanks!
Sample Data (Produced by above query)
P ID ESU_ID STATUS MOV_ID M_START M_END DESC Week1
1 ESU1 New 1M 01/01/2012 Boo Y
2 ESU2 New 2M 01/03/2012 Boo N
Desired output (Week1 – Week 52)
P ID ESU_ID STATUS MOV_ID M_START M_END DESC Week1 Week2
1 ESU1 New 1M 01/01/2012 Boo Y Y
2 ESU2 New 2M 01/03/2012 Boo N N
I suspect that the reason creating a WK2 join like WK1 didn’t work was that the column PRD_CAL_ID didn’t have a table alias on it. However, as you guessed, 52 joins is probably not going to perform very well. Try the following:
This produces slightly different results than your original query, having a WEEK_DESC instead of trying to create 52 different columns, one for each week, but I think it will perform better.
Share and enjoy.