简体   繁体   中英

Joining a sql table rows with all other rows of same table

I'm beginner in SQL Server querying. I have assigned to a task where I need to self join a table.

在此处输入图片说明

Above is table structure. And I need result as below. I have tried using self join , sub query etc. I couldn't get result.

ReqStatusId ReqStatus ChildId  ChildReqStatus
1           Open      2        On Hold 
1           Open      3        Closed  
2           On Hold   1        Open       
2           On Hold   3        Closed  
3           Closed    1        Open       
3           Closed    2        On Hold  

Result should come as: Each row in a table should joined with all other rows

use CROSS JOIN , Which gives you the Cartesian product between two tables

Select * 
From YourTable A
CROSS JOIN YourTable B
Where A.ReqStatusId <> B.ReqStatusId 

What you are trying to get is achieved through a cross join . If you select the table twice you would get the desired result.

select a.reqstatusid, a.reqstatus, b.reqstatusid as childreqstatusid,
b.reqstatus as childreqstatus
from table a, table b
where a.reqstatusid <> b.reqstatusid

You should do a JOIN on ReqStatusId <> ReqStatusId :

WITH Tbl(ReqStatusId, ReqStatus) AS(
    SELECT 1, 'Open' UNION ALL
    SELECT 2, 'On Hold' UNION ALL
    SELECT 3, 'Closed'
)
SELECT
    t1.*,
    ChildId = t2.ReqStatusId,
    ChildReqStatus = t2.ReqStatus
FROM Tbl t1
INNER JOIN Tbl t2
    ON t2.ReqStatusId <> t1.ReqStatusId
select a.reqstatusid, a.reqstatus, b.reqstatusid,
b.reqstatus
from table a
inner join table b on A.ReqStatusId = B.ReqStatusId 
Where A.ReqStatusId <> B.ReqStatusId 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM