I have a complex query, that will eventually have an output of this:
Table A:
| Job Number | Process Step A | Process Step B | Process Step C |
|---|---|---|---|
| Job A | Waiting | Completed | Waiting |
| Job B | In Process | Completed | Waiting |
| Job C | Completed | Waiting | Waiting |
I have a subquery table left joined that has the LAST Transaction for each of these jobs at each of these steps, that looks like this:
Table B:
| Job Number | Process Step | Status |
|---|---|---|
| Job A | Process Step A | Waiting |
| Job A | Process Step B | Completed |
| Job A | Process Step C | Waiting |
| Job B | Process Step A | In Process |
| Job B | Process Step B | Completed |
| Job B | Process Step C | Waiting |
| Job C | Process Step A | Completed |
| Job C | Process Step B | Waiting |
| Job C | Process Step C | Waiting |
I'm trying to do a case statement that basically says "If you find the status of Process Step A on Table B matching Table A's Job Number and column name, then use that Status, else show 'N/A'"
Here is the code (this is a small part of the whole thing):
SELECT CASE
WHEN SOI.[ValueStream] = '2D' or SOI.[ValueStream] = 'TS' THEN '2D/TS'
ELSE '3D'
END AS [VS],
CASE
WHEN Holds.[HoldSteps] like '%Pouch Pulling%' THEN 'Hold'
WHEN SOI.[Pouch Pulling Time] = 0 THEN 'N/A'
WHEN --Problem to build code here
ELSE 'Waiting'
END AS [PPStat]
FROM
(
SELECT A.[Job Number], A.[Product], A.[Quantity], A.[Release Week]
FROM [Job Planning Info] AS A
WHERE A.[Released] = 'Yes'
UNION ALL
SELECT B.[Remake Job Number], A.[Product], B.[Remake Quantity], A.[Release Week]
FROM [Remake Tracker] AS B
INNER JOIN
[Job Planning Info] AS A ON A.[Job Number] = B.[Original Job Number]
WHERE A.[Release Week] is not null
) AS JobList
LEFT JOIN
(
SELECT [Job Number], STRING_AGG(CAST([Process Step] as NVARCHAR(MAX)), ',') AS HoldSteps
FROM [Hold Tracker]
GROUP BY [Job Number]
) AS Holds
ON JobList.[Job Number] = Holds.[Job Number]
LEFT JOIN [Second Ops Info] AS SOI
ON Joblist.[Product] = SOI.[Part Number]
LEFT JOIN
(
SELECT DISTINCT JTL.[Job Number], JTL.[Process Step],
CASE
WHEN JTL.[Transaction Type] like '%Start Job%' THEN 'IP'
WHEN JTL.[Transaction Type] like '%Job Completed%' THEN 'Completed'
ELSE 'Waiting'
END AS [TranslatedStat]
FROM [Job Transaction List] JTL
WHERE JTL.[Job Number] <> '' and JTL.[TimeStamp] >= DATEADD(Month, -1, GETDATE())
and JTL.[TimeStamp] =
(
SELECT MAX(JTL2.[TimeStamp])
FROM [Job Transaction List] JTL2
WHERE JTL.[Job Number] = JTL2.[Job Number] and JTL.[Process Step] = JTL2.[Process Step]
)
ORDER BY JTL.[Job Number], JTL.[Process Step]
) AS ProcStepStats
ON JobList.[Job Number] = ProcStepStats.[Job Number]
LEFT JOIN [Live Schedule Automatic Pull] AS LSAP
ON JobList.[Job Number] = LSAP.[Job Number]
I was thinking of not sharing the code, but it probably makes more sense with it in there even though it's a lot more information in the code than what I'm actually asking for here.
Any help appreciated.