[英]use mysql SUM() in a WHERE clause
suppose I have this table 假设我有这张桌子
id | cash
1 200
2 301
3 101
4 700
and I want to return the first row in which the sum of all the previous cash is greater than a certain value: 我想要返回所有先前现金总和大于某个值的第一行:
So for instance, if I want to return the first row in which the sum of all the previous cash is greater than 500, is should return to row 3 因此,例如,如果我想要返回所有先前现金总和大于500的第一行,则应返回第3行
How do I do this using mysql statement? 我如何使用mysql语句执行此操作?
using WHERE SUM(cash) > 500
doesn't work 使用
WHERE SUM(cash) > 500
不起作用
You can only use aggregates for comparison in the HAVING clause: 您只能在HAVING子句中使用聚合进行比较:
GROUP BY ...
HAVING SUM(cash) > 500
The HAVING
clause requires you to define a GROUP BY clause. HAVING
子句要求您定义GROUP BY子句。
To get the first row where the sum of all the previous cash is greater than a certain value, use: 要获得所有先前现金总和大于某个值的第一行,请使用:
SELECT y.id, y.cash
FROM (SELECT t.id,
t.cash,
(SELECT SUM(x.cash)
FROM TABLE x
WHERE x.id <= t.id) AS running_total
FROM TABLE t
ORDER BY t.id) y
WHERE y.running_total > 500
ORDER BY y.id
LIMIT 1
Because the aggregate function occurs in a subquery, the column alias for it can be referenced in the WHERE clause. 因为聚合函数发生在子查询中,所以可以在WHERE子句中引用它的列别名。
Not tested, but I think this will be close? 未经测试,但我认为这将会接近?
SELECT m1.id
FROM mytable m1
INNER JOIN mytable m2 ON m1.id < m2.id
GROUP BY m1.id
HAVING SUM(m1.cash) > 500
ORDER BY m1.id
LIMIT 1,2
The idea is to SUM up all the previous rows, get only the ones where the sum of the previous rows is > 500, then skip one and return the next one. 想法是对所有先前的行进行求和,仅得到前一行的总和> 500的那些行,然后跳过一行并返回下一行。
In general, a condition in the WHERE
clause of an SQL query can reference only a single row. 通常,SQL查询的
WHERE
子句中的条件只能引用单个行。 The context of a WHERE
clause is evaluated before any order has been defined by an ORDER BY
clause, and there is no implicit order to an RDBMS table. 在
ORDER BY
子句定义任何顺序之前评估WHERE
子句的上下文,并且对RDBMS表没有隐式顺序。
You can use a derived table to join each row to the group of rows with a lesser id
value, and produce the sum of each sum group. 您可以使用派生表将每行连接到
id
值较小的行组,并生成每个sum组的总和。 Then test where the sum meets your criterion. 然后测试总和是否符合您的标准。
CREATE TABLE MyTable ( id INT PRIMARY KEY, cash INT );
INSERT INTO MyTable (id, cash) VALUES
(1, 200), (2, 301), (3, 101), (4, 700);
SELECT s.*
FROM (
SELECT t.id, SUM(prev.cash) AS cash_sum
FROM MyTable t JOIN MyTable prev ON (t.id > prev.id)
GROUP BY t.id) AS s
WHERE s.cash_sum >= 500
ORDER BY s.id
LIMIT 1;
Output: 输出:
+----+----------+
| id | cash_sum |
+----+----------+
| 3 | 501 |
+----+----------+
When using aggregate functions to filter, you must use a HAVING statement. 使用聚合函数进行筛选时,必须使用HAVING语句。
SELECT *
FROM tblMoney
HAVING Sum(CASH) > 500
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.