sql连接表及其子表

时间:2013-02-18 14:20:56

标签: sql sql-server

假设以下示例表:

+-----+-----+-----+
| ID1 | ID2 | VAL |
+-----+-----+-----+
| A   | X   | 1   |
| A   | Y   | 2   |
| A   | Z   | 3   |
| B   | X   | 4   |
| B   | Z   | 5   |
| C   | Y   | 6   |
+-----+-----+-----+

说我对ID1 = B感兴趣,并希望将其与其他人进行比较。所需的输出是:

+---------+---------+---------+---------+---------+---------+---------+
| REF.ID1 | OTH.ID1 | REF.ID2 | REF.ID2 | REF.VAL | OTH.VAL |  DIFF   |
+---------+---------+---------+---------+---------+---------+---------+
| B       | A       | X       | X       | 4       | 1       |  3      |
| B       | A       | NULL    | Y       | NULL    | 2       | -2      |
| B       | A       | Z       | Z       | 5       | 3       |  2      |
| B       | B       | X       | X       | 4       | 4       |  0      |
| B       | B       | Z       | Z       | 5       | 5       |  0      |
| B       | C       | NULL    | Y       | NULL    | 6       | -6      |
+---------+---------+---------+---------+---------+---------+---------+

谢谢。

2 个答案:

答案 0 :(得分:2)

您需要的是交叉加入:

SELECT Ref.Id, Oth.id, ......
FROM dbo.tbl AS Ref
CROSS JOIN dbo.tbl AS Oth
WHERE Ref.Id = 'B';

有关联接的更多信息,请查看我的博客系列:http://sqlity.net/en/1146/a-join-a-day-introduction/

此处描述了交叉加入:http://sqlity.net/en/1183/a-join-a-day-the-cross-join/

答案 1 :(得分:1)

这应该做:

SELECT  A.ID1 [REF.ID1],
        A.ID1 [OTH.ID1],
        CASE WHEN A.ID2 = B.ID2 THEN A.ID2 ELSE NULL END [REF.ID2],
        B.ID2 [OTH.ID2],
        CASE WHEN A.ID2 = B.ID2 THEN A.VAL ELSE NULL END [REF.VAL],
        B.VAL [OTH.VAL],
        CASE WHEN A.ID2 = B.ID2 THEN A.VAL ELSE 0 END - B.VAL [DIFF]
FROM (  SELECT *
        FROM YourTable
        WHERE ID1 = 'B') A
CROSS JOIN YourTable B