For example, this is a table about user participation activities that each event will score for the user:
User 1 participated in activity A, rating 100;
User 2 participated in activity B, rating 98, and participated in D activity, rating 10;
User 3 participated in activity C, rating 99
Requirements: The above four data according to each user's total score in descending order
Sql:
SELECT SUM (Score), user_id,campaign_id from table name GROUP by (user_id) ORDER by SUM (score) DESC;
The result is:
To complete the requirements, here are the small problems that the actual application encounters:
**dao.xml:
Note: Because sum () is a function, so the value should be used to receive the map, but we need to be in descending order, map is unordered, with the map to receive it is not to do hard? Don't worry, in DAO we encapsulate one more layer:
**dao.java:
Take him with ArrayList to receive, map do generics, so not afraid of its order change, by the way to paste the implementation of the value method in the class:
**serviceimpl. Java:
foreach Loop, but if you take the sum (score), just like the previous row to take contacts_id, to run the string type will be error, you need to use integer to do the conversion, so that the value is not reported abnormal.
The sum () function of MySQL