简体   繁体   中英

How to write the sql select query for this?

i have mssql tabel like this >

ID           Code                Rating
1            10                  4
2            10                  5
3            10                  4
4            11                  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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM