[英]Joining a sql table rows with all other rows of same table
I'm beginner in SQL Server querying. 我是SQL Server查询的新手。 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 使用
CROSS JOIN
,这将为您提供两个表之间的笛卡尔积
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
. 您想要得到的是通过
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
: 您应该对
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.