在下面的示例中表className中有如下分类
具体示例
classID className
衣服
裤子
帽子
鞋子
表productInfo有如下记录
productID productName parentID clickNum
男士衣服 ——衣服类别中这条记录的点击率最高
女士衣服
男士裤子
女士裤子
——裤子类别中这条记录点击率最高
男士帽子
女士帽子
帽子类别中这条点击率最高
男士鞋子
——鞋子类别中这条点击率最高
女士鞋子
女士鞋子
现在我们要求分别把衣服裤子帽子鞋子这些类别中点击率最高的一条记录找出来然后再降序排列结果如下
productID productName clickNum
男士衣服
女士裤子
男士鞋子
女士帽子
实现方法
declare @temp table
(
productID int
productName nvarchar()
clickNum int
)
declare @classID int
declare cursor_classID cursor
for
select classID from dboclassName
open cursor_classID
fetch next from cursor_classID into @classID
—— 表示 FETCH 语句成功
while @@FETCH_STATUS=
begin
insert into @temp
select top productIDproductNameclickNum from dboproductInfo
where parentID = @classID
order by clickNum desc
fetch next from cursor_classID into @classID
end
close cursor_classID
deallocate cursor_classID
select * from @temp order by clickNum desc