i have mssql tabel like this >
ID Code Rating
1 10 4
2 10 5
3 10 4
4 11 开发者_JAVA技巧 2
5 11 3
The sql query logic i want ...
I want when i search the record using code 10 then the output would be 4 because the 4 rating would be given most of the time for code 10 ....
and another logic if i search for code 11 then the out put will be 3 because 3 will be most recent rate for code 11...
how to write the sql query for im using ASP.NET ( VB)
The first thing you want to do is filter:
SELECT * FROM mytable WHERE Code = 10
You're interested in the 'rating' field:
SELECT Rating FROM mytable WHERE Code = 10
Now you want to count entries for Rating, which can be achieved using a combination of GROUP BY
and the COUNT()
function:
SELECT COUNT(*), Rating FROM mytable WHERE Code = 10 GROUP BY Rating
Now all that's left is sort by count, descending, and select only the first row:
SELECT TOP 1 Rating FROM mytable WHERE Code = 10 GROUP BY Rating ORDER BY COUNT(*) DESC
精彩评论