Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
mysql-在列值对应的行之间减去值_Mysql_Sql_Subtraction - Fatal编程技术网

mysql-在列值对应的行之间减去值

mysql-在列值对应的行之间减去值,mysql,sql,subtraction,Mysql,Sql,Subtraction,我有一张像这样的桌子: Number | Event | Weight 1 4 150 1 4 160 2 5 200 2 4 200 3 6 190 3 6 195 对于每一行,我想从其权重中减去另一行的权重,其中编号和事件匹配(如果存在)。所需输

我有一张像这样的桌子:

Number  |  Event  |  Weight
1            4          150
1            4          160
2            5          200
2            4          200
3            6          190
3            6          195
对于每一行,我想从其
权重
中减去另一行的
权重
,其中
编号
事件
匹配(如果存在)。所需输出为:

Number  |  Event  |  Weight  | DIFF
1            4          150    -10
1            4          160     10
2            5          200    NULL
2            4          200    NULL
3            6          190     -5
3            6          195      5

这样的手术可能吗?不确定是否相关,最终我需要将此查询转换为
视图
。提前感谢。

只需减去联接表中的列即可。当其中一个操作数为空时,算术运算的结果为空:

select a.Number, a.Event, a.Weight, a.Weight - b.Weight as DIFF
from a
left join b on a.Number = b.Number and a.Event = b.Event

它可以通过简单地减去联接表中的列来完成。当其中一个操作数为空时,算术运算的结果为空:

select a.Number, a.Event, a.Weight, a.Weight - b.Weight as DIFF
from a
left join b on a.Number = b.Number and a.Event = b.Event
您需要左联接:

select 
  t.*,
  t.weight - tt.weight diff
from tablename t left join tablename tt
on tt.number = t.number and tt.event = t.event and tt.weight <> t.weight
选择
t、 *,
t、 重量-tt.重量差
从tablename t左连接tablename tt
关于tt.number=t.number和tt.event=t.event和tt.weight t.weight
您需要左连接:

select 
  t.*,
  t.weight - tt.weight diff
from tablename t left join tablename tt
on tt.number = t.number and tt.event = t.event and tt.weight <> t.weight
选择
t、 *,
t、 重量-tt.重量差
从tablename t左连接tablename tt
关于tt.number=t.number和tt.event=t.event和tt.weight t.weight

如果表中包含3行或更多行的数字和事件组合相同,结果应该是什么?我忽略了注意,表中只有1个其他匹配项,如果表中包含3行或更多行的数字和事件组合相同,结果应该是什么?我忽略了注意,只有表中还有1个匹配项