Click here to Skip to main content
15,894,180 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dear Experts,

I have a Table Give below,
ITEM_ID | RATING
-----------------
   1	|   5	 
   1	|   2	 
   1	|   5	
   1	|   1	 
   2	|   5	
   2	|   5	 
   2	|   5	
   3	|   4	 


I need a Sql query to get the Item_ID of largest sum of Rating...

Eg....
Sum of First Items Ratings = 5 + 2 + 5 + 1 = 13

Sum of Second Items Ratings = 5 + 5 + 5    = 15

Sum of Third Items Ratings = 4

So my out put is = Item_ID = 2 

Coz, it having the highest rating 15 ...


PLease help me..

Thanks...

Dileep
Posted

You can get your result using follwong Query

SQL
SELECT ITEM_ID, MAX(SUM(RATING)) AS HighestRate FROM TableName 
GROUP BY ITEM_ID
 
Share this answer
 
To get proper rating, i would suggest you to use RANK()[^] function in case if two (or more) Items will get the same count of points (rating).

SQL
SELECT ITEM_ID, Points, RANK() OVER(ORDER BY Points DESC) AS [Rank]
FROM (
    SELECT ITEM_ID, SUM(RATING) AS Points
    FROM TableName
    GROUP BY ITEM_ID) AS T


More about: Ranking functions[^]
 
Share this answer
 
v2
Hi,

Use the below query i hope it will give you result as per your expection.

SQL
select ITEM_ID, Sum(RATING) As TotalRATING, Rank() over (order by Sum(RATING) desc) as CurrentRank from TableName group by ITEM_ID


OutPut-

ITEM_ID |TotalRATING |CurrentRank
2 | 15 | 1
1 | 13 | 2
3 | 4 | 3


Thanks

Zubair
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900