SQL Server:在同一个表上具有相同元素的ID对

时间:2013-11-11 12:23:27

标签: sql sql-server-2005

我正在使用SQL Server 2005。

我有一个表INVENTORY,其中包含ProductId, BranchId, Stock

我想选择具有完全相同产品的BranchId对。

例如

BranchId - ProductId
1 - a
1 - b
1 - c
2 - b
2 - c
3 - a
3 - b
3 - c

必须返回元组

Inventory1.BranchId - Inventory2.BranchId
1 - 3
3 - 1

如果一对在两个元组(1-3和3-1)中重复,则不构成。

这个想法是:

SELECT I1.BranchId,I1.ProductId,I2,BranchId,I2.ProductId
FROM inventory AS I1,inventory as I2
WHERE I1.BranchId<>I2.BranchId AND
"I1.ProductId's Exists in the products list of I2" //This is the part I don't know how to do

有什么想法吗?

由于

1 个答案:

答案 0 :(得分:0)

您可以使用CTE执行此操作。主要思想是连接每个分支的产品列表,然后将此CTE与其自身连接起来:

WITH InventoryCTE
AS
(
    SELECT
        I1.BranchId
        , STUFF(
           (SELECT
                ', ' + I2.ProductId
                FROM Inventory I2
                WHERE I1.BranchId = I2.BranchId
                ORDER BY I2.ProductId
                FOR XML PATH(''), TYPE
           ).value('.','varchar(max)')
           ,1,2, ''
            ) AS ProductIds
    FROM Inventory I1
    GROUP BY I1.BranchId
)
SELECT I1.BranchId, I2.BranchId, I2.ProductIds
FROM
    InventoryCTE I1
    INNER JOIN InventoryCTE I2 ON I2.ProductIds = I1.ProductIds
WHERE I1.BranchId != I2.BranchId