0

我正在研究游标。我想创建一个光标来显示每个客户的信息和他购买的更多产品。为此,我编写了以下游标:

declare myCursor cursor
 for select Customers.CustomerID, Customers.ContactName, Products.ProductName, SUM(Quantity) as Total
  from Customers inner join Orders on Customers.CustomerID = Orders.CustomerID
 inner join( [Order Details] inner join Products on [Order Details].ProductID = Products.ProductID)
 on Orders.OrderID = [Order Details].OrderID
 group by Customers.CustomerID, Customers.ContactName, Products.ProductName
 --
 declare @CustomerID nchar(10), @ContactName nvarchar(30), @ProductName nvarchar(4), @Total int
 open myCursor
 fetch next from myCursor into @CustomerID, @ContactName , @ProductName, @Total
 while @@FETCH_STATUS = 0
     begin

     begin
          print @CustomerID+' '+@ContactName+' '+@ProductName+' '+CAST(@Total as varchar)
          fetch next from myCursor into @CustomerID, @ContactName , @ProductName, @Total
     end
     end

现在它显示每个客户购买每种产品的次数。现在我想使用 IN、CONTAIN 或 EXISTS 等条件关键字来完成我的光标,以显示每个客户购买了更多的产品。但我不知道这样做。你能帮帮我吗?

4

1 回答 1

0

如果我理解正确,您希望展示每位客户购买次数最多的产品。使用光标,您可以通过首先声明一个表变量来做到这一点,例如

declare @customersprocessed table
(
  @CustomerID
)

然后,您需要对光标进行排序,SUM(Quantity) DESC以便顶部项目上升到顶部。

最后,您需要将查询的内部部分修改为仅在表中不存在客户 ID 时才打印,然后将客户 ID 添加到表中,这样就不会再次打印。

 begin
      if ((select count(1) from @customersprocessed where CustomerID = @CustomerID) = 0)
      begin
         print @CustomerID+' '+@ContactName+' '+@ProductName+' '+CAST(@Total as varchar)
      end
      else
      begin
         insert into @customersprocessed select @CustomerID
      end

      fetch next from myCursor into @CustomerID, @ContactName , @ProductName, @Total
 end

这当然是假设您要保留光标。还有其他方法可以使用您要显示的所有客户的选择和返回购买最多的产品的子查询。

于 2010-09-01T20:39:03.763 回答