The sum () function of MySQL

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.