如何在mySQL中正确包装sum(quantity)= max(sum(quantity))?

时间:2015-02-26 15:37:17

标签: mysql

我想要获取每个唯一属性的总和,然后取这些值的最大值。有关如何使用mySQL执行此操作的任何建议?我一直在“无效使用群组功能”。

+-------------+-------------+------+-----+---------+-------+
| Field       | Type        | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| matchName   | varchar(26) | YES  | MUL | NULL    |       |
| winner      | varchar(26) | YES  |     | NULL    |       |
| loser       | varchar(26) | YES  |     | NULL    |       |
| winningGame | varchar(26) | YES  |     | NULL    |       |
| dateofWin   | date        | YES  |     | NULL    |       |
+-------------+-------------+------+-----+---------+-------+

+------------+-------------+------+-----+---------+-------+
| Field      | Type        | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+-------+
| matchName  | varchar(26) | NO   | PRI |         |       |
| date       | date        | YES  |     | NULL    |       |
| grandPrize | int(11)     | YES  |     | NULL    |       |
| location   | varchar(26) | YES  |     | NULL    |       |
| state      | varchar(26) | YES  |     | NULL    |       |
| attendance | int(11)     | YES  |     | NULL    |       |
+------------+-------------+------+-----+---------+-------+

我到目前为止最接近的是使用:

select Results.winner, Tourney.grandPrize 
from Tourney 
inner join Results 
on Results.matchName=Tourney.matchName;

1 个答案:

答案 0 :(得分:1)

你的问题很不清楚,

我赞成@ A.D。注释,您应该提供更多详细信息,表结构,数据样本,预期结果,带来错误的当前查询等。

但你的问题的快速回答是:

SELECT t.*, MAX(t.sum_qty) as max_qty
FROM (
  SELECT *, SUM(qty) as sum_qty
  FROM test
  GROUP BY order_id // you can set any group field you need here
) AS t