如何在SQL Server查询中找到与其他产品畅销的产品

时间:2012-12-15 18:13:15

标签: sql sql-server

我有一张销售表

SALE_ID   |   Product_Code    |  Qty   |  Sales_Value  | Taxes ....
==========+===================+========+===============+=========
001       |   AAAA            |   1    |  1000         | 50     ....
001       |   BBBB            |   1    |  10           | 0.5
002       |   CCCC            |   1    |  30           | 1.5
002       |   AAAA            |   1    |  1000         | 1.5

我正在尝试获取一张表格,其中显示一件商品的销售次数与另一件具有相同销售ID的产品(在同一张发票上销售)

Product ID  |  Product ID 2   |  Sales Together
============+=================+==================
AAAA        |  BBBB           |      1
AAAA        |  CCCC           |      1
BBBB        |  AAAA           |      1
BBBB        |  CCCC           |      0
CCCC        |  AAAA           |      1
CCCC        |  BBBB           |      0

我正在使用MS SQL,我想我必须按照销售进行分组查询,然后是产品ID,但这就是我对如何跨计数销售感到困惑。

如果方便的话,我也有一张产品大师表

Product_ID   |  Description    |
=============+=================|
AAAA         | Battery         |
BBBB         | Flashlight      |
CCCC         | Radio           |

1 个答案:

答案 0 :(得分:4)

我认为应该这样做

SELECT P1.Product_Code,
       P2.Product_Code,
       Count(DISTINCT S1.SALE_ID)
FROM   Product P1
       JOIN Product P2
         ON P1.Product_Code > P2.Product_Code
       LEFT JOIN Sales S1
                 INNER JOIN Sales S2
                   ON S1.SALE_ID = S2.SALE_ID
         ON S1.Product_Code = P1.Product_Code
            AND S2.Product_Code = P2.Product_Code
GROUP  BY P1.Product_Code,
          P2.Product_Code