0

My table consists of all order history like this:

table: orderhistory

OrderID       ProductID       CustomerID        Quantity        
     1                   4                       1                        1
     1                   5                       1                        2
     1                   6                       1                        1
     2                   4                       2                        1
     2                   3                       2                        1
     2                   5                       2                        1

OrderID and ProductID are primary keys.
So purchase history related to product 4 consists of product 3, 5 and 6. And product 5 should be prior to other records as it appears twice together with 4 in a single order. How can I use a single query to grab that information?

Desired result: (query for related history of product 4)

ProductID       Freq       
     5                   2
     6                   1
     3                   1
4

2 回答 2

1
select ProductID, count(ProductID) as Freq from orderhistory group by ProductID;

您可以根据需要放置在哪里,例如..

select ProductID, count(ProductID) as Freq from orderhistory 
where ProductID in (5,6,3) group by ProductID;

或者

select ProductID, count(ProductID) as Freq from orderhistory 
where ProductID != 4 group by ProductID;
于 2012-07-09T09:45:57.277 回答
1

以下查询将获取必要的数据。

SELECT 

      DISTINCT PRODUCTID

 FROM 

      [ORDERHISTORY] oh

 WHERE

      oh.OrderID IN (SELECT ORDERID FROM ORDERHISTORY WHERE PRODUCTID = 4 )
于 2012-07-09T09:42:44.567 回答