DROP TABLE IF EXISTS #table1;
CREATE TABLE #table1 ( col1 int NOT NULL, col2 varchar(30) NULL,
col3 varchar(30) NULL );
INSERT INTO #table1 VALUES
(123, 'ABC', 'Submitted'),
(456, 'DEF', 'Submitted'); --++
DROP TABLE IF EXISTS #table2;
CREATE TABLE #table2 ( col1 int NOT NULL, col2 varchar(30) NULL,
col3 varchar(30) NULL, col4 varchar(10) NULL );
INSERT INTO #table2 VALUES
(123, 'ABC', 'Completed', 'A'),
(123, 'ABC', 'Completed', 'B'),
(123, 'ABC', 'Completed', 'A'),
(123, 'ABC', 'Completed', 'B'),
(456, 'DEF', 'Completed', 'A'), --++
(456, 'DEF', 'Completed', 'B'), --++
(456, 'DEF', 'In Progress', 'C'); --++
;WITH cte_table2_status AS (
SELECT col1, CASE WHEN COUNT(*) = SUM(CASE WHEN col3 = 'completed'
THEN 1 ELSE 0 END) THEN 1 ELSE 0 END AS are_all_complete
FROM #table2
GROUP BY col1
)
SELECT ca1.*
FROM #table1 t1
INNER JOIN cte_table2_status ct2 ON ct2.col1 = t1.col1
CROSS APPLY (
SELECT t1.col1, t1.col2, t1.col3, NULL AS col4
WHERE ct2.are_all_complete = 0
UNION ALL
SELECT t2.col1, t2.col2, t2.col3, t2.col4
FROM #table2 t2
WHERE t2.col1 = ct2.col1 AND ct2.are_all_complete = 1
) AS ca1