-1

假设以下示例表:

+-----+-----+-----+
| 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      |
+---------+---------+---------+---------+---------+---------+---------+

谢谢你。

4

2 回答 2

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/

于 2013-02-18T14:23:46.257 回答
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
于 2013-02-18T14:31:29.157 回答