社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  DATABASE

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

machump • 5 年前 • 1933 次点击  

我有一张桌子像:

Number  |  Event  |  Weight
1            4          150
1            4          160
2            5          200
2            4          200
3            6          190
3            6          195

对于每一行,我想从它的 Weight , the 重量 在另一排 Number Event 匹配项(如果存在)。所需输出为:

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

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

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/43261
 
1933 次点击  
文章 [ 2 ]  |  最新文章 5 年前
jspcal
Reply   •   1 楼
jspcal    6 年前

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

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
forpas
Reply   •   2 楼
forpas    6 年前

您需要左连接:

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