簡體   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