繁体   English   中英

将sql表行与同一表的所有其他行联接

[英]Joining a sql table rows with all other rows of same table

我是SQL Server查询的新手。 我已分配给需要自行加入表的任务。

在此处输入图片说明

上面是表格结构。 我需要如下结果。 我尝试使用自连接,子查询等。我无法获得结果。

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  

结果应为:表中的每一行应与所有其他行合并

使用CROSS JOIN ,这将为您提供两个表之间的笛卡尔积

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

您想要得到的是通过cross join实现的。 如果您两次选择该表,则将获得所需的结果。

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

您应该对ReqStatusId <> ReqStatusId进行JOIN

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 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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