The following types are available in the table classname:
Classid classname
1 clothes
2 pants
5 hats
10 shoes
The table productinfo has the following records:
Productid productname parentid clicknum
1 men's clothes 1 90 -- the highest click rate of this record in the clothing category
2 ladies clothes 1 80
3 men's trousers 2 70
4. Ladies pants 2 90 -- the highest click rate of this record in the trousers category
5 men's hats 5 15
6 ladies hats 5 30 -- the highest click rate in the hat category
7 men's shoes 10 65-the highest click rate in the shoes category
8 women's shoes 10 52
9 ladies shoes 1 10 54
Now we need to find the records with the highest click rate among clothes, trousers, hats, and shoes respectively, and sort them in descending order. The results should be as follows:
ProductID productName clickNum
1 men's clothes 90
4 ladies pants 90
7 men's shoes 65
6 ladies hats 30
The implementation process is as follows:
/*
Function: Search for the records with the highest click rate under each category in the category table [className], and sort these records in descending order.
Author: vivianhu
Sorting: kgdiwss (I just added comments and renamed some variables)
Date: 2006-4-17
*/
/* If a temporary table tTable exists, delete it first */
If exists (
Select * from dbo. sysobjects
Where id = object_id (n' [dbo]. [tTable] ') and OBJECTPROPERTY (id, n' isusertable') = 1
)
Drop table [dbo]. [tTable]
GO
/* Create a temporary table */
Create table tTable
(
Productid int,
Productname varchar (10 ),
Clicknum int
)
/* Variable Declaration */
Declare @ classID int
/* Define the cursor */
Declare cursor_classID
CURSOR
SELECT classID FROM className
/*
Open cursor
@ FETCH_STATUS
Returns the status of the last cursor executed by the FETCH statement, rather than the status of any cursor currently opened.
0 indicates that the FETCH statement is successful.
*/
OPEN cursor_classID
Fetch next from cursor_classID INTO @ classID
WHILE @ FETCH_STATUS = 0
/* Search for a record with the highest click rate in a category */
BEGIN
Insert into tTable
Select top 1 productID, productName, clickNum from productInfo
Where parentID = @ classID
Order by clickNum desc
Fetch next from cursor_classID
INTO @ classID
END
/* Close the cursor */
CLOSE cursor_classID
/* Delete cursor reference */
DEALLOCATE cursor_classID
/* Sort the records in the temporary table in descending order based on the click rate */
Select * from tTable order by clickNum desc
/* Delete a temporary table */
Drop table tTable