Hi @Matt Hardebeck ,
Welcome to Microsoft Q&A!
For this type of problem we recommend that you post CREATE TABLE statements for your tables together with INSERT statements with sample data, enough to illustrate all angles of the problem. We also need to see the expected result of the sample.
Please refer below example and check whether it is helpful to you.
create table reports
(
eqpsort int,
rownumber int,
sid varchar(20),
service_code varchar(10),
cat_component char(2),
eqp_cmp char(2))
insert into reports values
(1,28,'A','S1','CC','01'),
(1,28,'A','S1','DG','05'),
(1,28,'B','MY','03',null),
(1,28,'C','B3','CC','01'),
(1,28,'C','B3','DG','05'),
(2,28,'22001','BA001','01',NULL),
(2,28,'22004','HR608','03',NULL),
(2,28,'22008','EZ026','05',NULL),
(2,28,'22013','EM100','DG',NULL),
(2,28,'22014','EM100','DG',NULL)
;WITH CTE AS (
SELECT *,ROW_NUMBER() OVER (PARTITION BY eqpsort,rownumber,service_code,cat_component ORDER BY SID) RN1 FROM reports WHERE eqpsort=2)
,CTE1 AS (
SELECT *,ROW_NUMBER() OVER (PARTITION BY eqpsort,rownumber,cat_component,eqp_cmp ORDER BY SID) RN2 FROM reports WHERE eqpsort=1)
,CTE2 AS (
SELECT A.*,B.sid SID1,B.service_code service_code2,B.cat_component cat_component2,B.eqp_cmp eqp_cmp2
FROM CTE A INNER JOIN CTE1 B
ON A.cat_component=B.cat_component AND A.RN1=B.RN2 )
,CTE3 AS (
SELECT eqpsort,rownumber,SID,service_code,cat_component,eqp_cmp,SID1,service_code2,cat_component2,eqp_cmp2 FROM CTE2
UNION
SELECT A.eqpsort,A.rownumber,A.SID,A.service_code,A.cat_component,A.eqp_cmp,B.SID,B.service_code,B.cat_component,B.eqp_cmp
FROM CTE A INNER JOIN CTE1 B
ON A.cat_component=B.eqp_cmp AND A.RN1=B.RN2
WHERE NOT EXISTS
(SELECT 1 FROM CTE2 C WHERE B.cat_component=C.cat_component2 AND B.eqp_cmp=C.eqp_cmp2))
SELECT A.eqpsort,A.rownumber,A.service_code,A.cat_component,A.eqp_cmp
,B.SID1,B.service_code2,B.cat_component2,B.eqp_cmp2
FROM CTE A
LEFT JOIN CTE3 B ON A.SID=B.SID
Output:
eqpsort rownumber service_code cat_component eqp_cmp SID1 service_code2 cat_component2 eqp_cmp2
2 28 BA001 01 NULL A S1 CC 01
2 28 HR608 03 NULL B MY 03 NULL
2 28 EZ026 05 NULL NULL NULL NULL NULL
2 28 EM100 DG NULL A S1 DG 05
2 28 EM100 DG NULL C B3 DG 05
Best regards,
Melissa
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.