To achieve the desired output, you can use a combination of JOINs and subqueries in your SQL query. Here's the query that will provide you with the records you need:
SELECT
a.Job,
a.Suffix,
a.Item,
a.Qty,
b.OperNum,
b.WC,
c.Descr
FROM
SyteLine.dbo.A a
INNER JOIN (
SELECT
Job,
Suffix,
MAX(OperNum) AS MaxOperNum
FROM
SyteLine.dbo.B
WHERE
Comp = 1
GROUP BY
Job,
Suffix
) b_sub ON a.Job = b_sub.Job AND a.Suffix = b_sub.Suffix
INNER JOIN SyteLine.dbo.B b ON a.Job = b.Job AND a.Suffix = b.Suffix AND b.OperNum > b_sub.MaxOperNum AND b.Comp = 0
INNER JOIN SyteLine.dbo.C c ON b.WC = c.WC
WHERE
a.Release = 'R';
Explanation:
In the subquery b_sub
, we first filter Table B to get the maximum OperNum
for each Job
and Suffix
where Comp = 1
.
Next, we join Table A with the b_sub
subquery on Job
and Suffix
to get the relevant rows from Table A.
Then, we join Table B with Table A on Job
and Suffix
and add a condition to get the OperNum
that is greater than the MaxOperNum
from the b_sub
subquery and where Comp = 0
.
Finally, we join Table C to get the Descr
based on the WC
value from Table B.
This query will provide you with the desired output, showing the open jobs with open operations and the operation number that comes after the Comp = 1
operation for each job and suffix combination.
--please don't forget to upvote and Accept as answer if the reply is helpful--