1

我正在使用 MS SQL Server 2005 Express。我有表 INVENTORY,我想检索所有具有相同颜色的产品对(例如)。

所以,我有以下查询:

SELECT I1.ProdId,I2,ProdId FROM Inventory AS I1,Inventory AS I2
WHERE I1.Color=I2.Color
ORDER BY I1.ProdId

这将返回一些这样的:

ProdId|ProdId
-------------
   1  |  2
   1  |  3
   2  |  1
   2  |  3
   3  |  1
   3  |  2

我需要对称元组(如 1-2、2-1)只显示一个元组。

有人有想法吗?谢谢!

4

1 回答 1

0
SELECT I1.ProdId,
       I2,ProdId 
FROM Inventory AS I1,
     Inventory AS I2
WHERE I1.Color=I2.Color
  AND (
       -- here I get the rows without the symmetric 
       I1.ProdId || '-' || I2,ProdId <>  I2.ProdId || '-' || I1,ProdId 
       OR
       (
          -- here I get the rows with the symmetric but only with the first id 
          -- smaller than the second, so excluding 'duplication'
          I1.ProdId || '-' || I2,ProdId <>  I2.ProdId || '-' || I1,ProdId 
          AND
          I1.ProdId  < I2.ProdId 
       )
      )
ORDER BY I1.ProdId
于 2013-11-07T16:55:31.733 回答