0

我正在使用 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

任何想法?

谢谢

4

1 回答 1

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
于 2013-11-11T12:48:59.227 回答