我有一张销售表
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
我正在尝试获取一张表格,该表格显示一种产品与另一种具有相同销售编号(在同一张发票上出售)一起销售的次数
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 |
我认为应该这样做
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