gpt4 book ai didi

mysql - 将相同符号的连续值相加

转载 作者:行者123 更新时间:2023-11-29 01:59:45 25 4
gpt4 key购买 nike

一个非常新手的 mysql 问题。我有一个如下所示的 mysql 表,其中输出列是我要生成的内容

测试表

Record_ID  Day  price_change  Output
=======================================
1 1 null null
2 1 3 3
3 1 -1 null
4 1 0 -1
5 1 1 1
6 1 -1 null
7 1 0 null
8 1 0 -1
9 1 1 1
10 2 null null
11 2 1 null

我想要做的是在记录的 price_change 列中获取运行总计,并在每次值中的符号发生变化、日期发生变化或下一个值为 null 时输出该总计。

record_id 可能不总是连续的,所以它可能是 10、15、16、19、20 等。

我正在尝试执行类似下面的操作(我不处理日期变化),但它的行为并不像我预期的那样,我无法在输出后重置变量。任何人都可以指出我应该如何处理这个问题的正确方向吗?

set @var := 0;
SELECT
rid,
pcng,
CASE
when pcng > 0 and next_price_change > 0 then @var := @var + pcng /* output null */
when pcng < 0 and next_price_change < 0 then @var := @var + pcng /* output null */
when pcng * next_price_change < 0 or next_price_change is null then @var + pcng
/* how to reset the @var ??? */
END AS output_sum
FROM (
SELECT
Record_ID as rid,
Price_CHANGE as pcng,
/* Subselect next number from next Record_ID which may not be in sequence */
(SELECT Price_change FROM test_table WHERE Record_ID > rid ORDER BY Record_ID ASC LIMIT 1) AS next_price_change
FROM test_table
) pcalc

最佳答案

变量赋值在 mysql 中是从左到右计算的,所以有类似的东西

mysql> set @foo=1;
Query OK, 0 rows affected (0.00 sec)

会给你这个,动态更新整个字段列表的变量:

mysql> select @foo as first, @foo:=@foo+1 as second, @foo:=@foo+10 as third;
+-------+--------+-------+
| first | second | third |
+-------+--------+-------+
| 1 | 2 | 12 |
+-------+--------+-------+
1 row in set (0.00 sec)

请注意,现在变量开始为原始 1,然后更新为新值。然后,如果您重新运行相同的查询:

mysql> select @foo as first, @foo:=@foo+1 as second, @foo:=@foo+10 as third;
+-------+--------+-------+
| first | second | third |
+-------+--------+-------+
| 12 | 13 | 23 |
+-------+--------+-------+
1 row in set (0.00 sec)

您从上一个查询的LAST 赋值开始,然后再次更新它。

所以基本上,只需进行所有查询中计算,然后作为 SELECT 中的 LAST 字段,用新值更新变量。例如

SET @prev = null;
SELECT this + @prev, that - @prev, whatever * @prev, @prev := new_value

关于mysql - 将相同符号的连续值相加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18213670/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com