简体   繁体   English

SQL-如何在同一查询中使用SUM和MAX?

[英]SQL - How to use SUM and MAX in same query?

I am working with a MySQL database version 5.0.41 (and PHP 5.2.6, though that may not be relevant to this question). 我正在使用MySQL数据库版本5.0.41(和PHP 5.2.6,尽管可能与该问题无关)。

I have a table called votes with the following fields: id , item_id , vote_value . 我有一个名为votes的表,其中包含以下字段: iditem_idvote_value Each time a user on the site submits a positive vote for an item, a new row is created with the corresponding item_id and a positive number (ie 1). 每次用户在网站上对某项商品投赞成票时,都会使用相应的item_id和正数(即1)创建一个新行。 When the vote is negative, a row is created with the corresponding item_id and a negative number (ie -1). 当投票否定时,将创建一个具有相应item_id和一个负数(即-1)的行。 I'd like to select, with one query (if possible), the item_id that has the most votes. 我想通过一个查询(如果可能)选择投票最多的item_id。 To do this, I first need to sum up all the votes for each individual item_id (to get a number like 38 or -14) and then select the maximum for that number. 为此,我首先需要对每个单独的item_id所有票求和(以得到38或-14这样的数字),然后选择该数字的最大值。 I am not sure how to write the query for that. 我不确定如何为此编写查询。

Could you help? 你能帮忙吗?

Thanks! 谢谢!

SELECT item_id, SUM(vote_value) AS sum
FROM votes
GROUP BY item_id
ORDER BY sum DESC
LIMIT 1

You could do something like: 您可以执行以下操作:

SELECT item_id, SUM(vote_value) AS total, COUNT(id) AS c
FROM votes
GROUP BY item_id
ORDER BY total DESC, c DESC
LIMIT 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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