首页 文章

将sql表行与同一个表的所有其他行连接起来

提问于
浏览
2

我是SQL Server查询的初学者 . 我已经分配了一个我需要自己加入表格的任务 .

enter image description here

以上是表格结构 . 我需要结果如下 . 我尝试过使用自联接,子查询等 . 我无法得到结果 .

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

结果应为:表中的每一行都应与所有其他行连接

4 回答

  • 1

    你想要得到的是通过 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
    
  • 3

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

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

    你应该在 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
    
  • 0
    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
    

相关问题