在一些电子商务网站中,有时需要推荐最近几天发生的订单数据来计算商品推荐信息。在数据层我们需要写一些查询语句或存储过程。可以查出哪个订单出现的最频繁,然后降序排列,选出前5作为推荐商品。

 

 

Select ProductID,
   name,Description

 

   From Product
   WHERE ProductID IN
   (
      SELECT Top 5 Od2.ProductID
      FROM OrderDetails od1
      JOIN OrderDetails od2 ON
      od1.OrderID=od2.OrderID
      Where od1.ProductID=@ProductID and od2.ProductID!=@ProductID
      And DateDIFF(dd,Orders.DateCreated,GetDate())<30       

 

      Group by od2.ProductID
      ORDER By Count(od2.ProductID) DESC

)

 

这里用了表连接操作,用Orders表的两个实例进行连接,选择的是与Od2。ProductID一起订的商品还有哪些,这里ProductID!=@ProductID是删去与Od2.ProductID相同的商品号。然后根据哪个productID出现次数多少,降序排序,选择最大的前5位。

相关文章: