最小值/最大值"总和"与相对值

时间:2017-08-02 15:24:40

标签: mysql

我有下表<dependency> <groupId>com.google.code.findbugs</groupId> <artifactId>findbugs</artifactId> <version>3.0.1</version> </dependency>

test

对于MIN(值)我得到-5,对于MAX(值)我得到10,对于SUM(值)我得到1.但是,我希望在进行表步骤时获得最小值和最大值一步一步。

示例1:+----+-------+ | id | value | +----+-------+ | 1 | -3 | | 2 | -5 | | 3 | 10 | | 4 | -1 | +----+-------+

这应返回-8(第一行为-3,加上第二行-5导致所有值的最低值)。

示例2:SELECT AWESOME_FUNCTION_SUM_MIN(value) FROM test ORDER BY id ASC

这应该返回2(第一行-3,第二行-5和第三行+10导致所有值的最高值)。

显然,SELECT AWESOME_FUNCTION_SUM_MAX(value) FROM test ORDER BY id ASC并没有真正意义,因为它用于排序查询结果,但我仍然在这里使用它来进行演示。对我来说,这是一个基本的功能,所以我很惊讶没有发现它。我可能使用了错误的关键字。有人可以帮帮我吗?或者我是否必须提取所有值并在外部进行分析(=不使用MySQL)?

3 个答案:

答案 0 :(得分:0)

要获得累积总和,您可以将表连接到自身。

select min(val) 
  from (select sum(a.value) as val from test a join test b
    on a.id<=b.id group by b.id) t1;
/* answer: -8 */

select max(val)
  from (select sum(a.value) as val from test a join test b
    on a.id<=b.id group by b.id) t1;
/* answer: 2 */

答案 1 :(得分:0)

创建表/插入数据。

console.log("AkjkljKK".replace(/(?![A-Z])./g, ''));

MySQL没有这些功能,但您可以使用自联接来模拟它们。

查询SUM_MIN

CREATE TABLE test
    (`id` INT, `value` INT)
;

INSERT INTO test
    (`id`, `value`)
VALUES
    (1, -3),
    (2, -5),
    (3, 10),
    (4, -1)
;

<强>结果

SELECT 
 SUM(test.value)
FROM 
 test
INNER JOIN (
  SELECT 
   id
  FROM 
   test
  WHERE
   test.value > 0 
  ORDER BY 
   id ASC
  LIMIT 1 
)
 AS 
  positive_number
ON
 test.id < positive_number.id 
ORDER BY 
 test.id

查询SUM_MAX

sum(test.value)  
-----------------
-8               

<强>结果

SELECT 
 SUM(test.value)
FROM 
 test
INNER JOIN (
  SELECT 
   id
  FROM 
   test
  WHERE
   test.value > 0 
  ORDER BY 
   id ASC
  LIMIT 1 
)
 AS 
  positive_number
ON
 test.id <= positive_number.id  
ORDER BY 
 test.id 

答案 2 :(得分:0)

以这种方式:

SELECT x.*
     , @least:=LEAST(@least,value) least
     , @greatest:=GREATEST(@greatest,value) greatest
     , @i:=@i+value running 
  FROM my_table x 
     , (SELECT @least:=1000,@greatest:=-1000,@i:=0) vars 
 ORDER 
    BY id;
+----+-------+-------+----------+---------+
| id | value | least | greatest | running |
+----+-------+-------+----------+---------+
|  1 |    -3 |    -3 |       -3 |      -3 |
|  2 |    -5 |    -5 |       -3 |      -8 |
|  3 |    10 |    -5 |       10 |       2 |
|  4 |    -1 |    -5 |       10 |       1 |
+----+-------+-------+----------+---------+