I am a novice at this, nor is this my data. We are trying to pull multiple records into one record for query results.
To simplify the tables and amount of data, the following two tables should be sufficient:
Table 1
PRVDR_NUM | RPT_REC_NUM
013 1234
014 4567
Table 2
RPT_REC_NUM | WKSHT_CD | LINE_NUM | ITM_VAL_NUM
1234 f1 3 30
1234 f1 9 3
1234 e2 100 100
4567 f1 3 20
4567 f1 9 8
4567 e2 100 100
The first part is to get all records where the ITM_NUM_CAL is between 25 and 50 for WKSHT_CD f1 and LINE_NUM 3, that ITM_NUM_VAL is revenue.
SELECT r.PRVDR_NUM as Provider,
r.RPT_REC_NUM as 'Report Record',
n.ITM_VAL_NUM as Revenue
FROM Table 1 r
left outer join Table 2 n on
r.RPT_REC_NUM = n.RPT_REC_NUM
WHERE (n.WKSHT_CD = 'f1') and (n.LINE_NUM = '3')
and (n.ITM_VAL_NUM > 25) and (n.ITM_VAL_NUM < 50)
and left(r.PRVDR_NUM, 2) in ('01','04','11','18','25','26','34','44','49')
So our results are:
Provider | Report Record | Revenue
013 1234 30
But we also want to be able to pull the corresponding ITM_VAL_NUM for WKSHT_CD f1 and LINE_NUM 9, which we’ll call cost.
So the results should be:
Provider | Report Record | Revenue | Cost
013 1234 30 3
Much thanks in advance.
EDIT
I believe this is the final query I was looking for after some maneuvering and the addition of a new variable, CLMN_NUM, which is another column in table2.
SELECT r.PRVDR_NUM as Provider,
r.RPT_REC_NUM as 'Report Record',
n.ITM_VAL_NUM as Revenue,
n2.ITM_VAL_NUM as 'Cost',
n3.ITM_VAL_NUM as 'Visits'
FROM table1 r
LEFT OUTER JOIN table2 n on r.RPT_REC_NUM = n.RPT_REC_NUM
LEFT OUTER JOIN table2 n2 on n.WKSHT_CD = n2.WKSHT_CD
and n.RPT_REC_NUM = n2.RPT_REC_NUM and n2.LINE_NUM = 9
LEFT OUTER JOIN table2 n3 on r.RPT_REC_NUM = n3.RPT_REC_NUM
and n3.WKSHT_CD = 'e2' and n3.LINE_NUM = 100 and n3.CLMN_NUM = xxxx
WHERE (n.WKSHT_CD = 'f1')
AND (n.LINE_NUM = '3')
AND (n.ITM_VAL_NUM > 25)
AND (n.ITM_VAL_NUM < 50)
AND left(r.PRVDR_NUM, 2) in ('01','04','11','18','25','26','34','44','49')
A couple ways:
Subquery
Another JOIN