SQLITE 视图,如何计算同一行买卖之间的差异

SQLITE view, how to calculate diff between buy and sell into same row

我对使用 sqlite studio 的这个 (sqlite) 很陌生。 我有一个包含很多行的 table,试图查看日期、对象、购买价格、销售价格和差异。

这就是我得到的

DATE    OBJ     BOUGHT  SOLD    DIFF
2009    OBJ1    235000  NULL    NULL
2012    OBJ2    255500  NULL    NULL
2021    OBJ3    305400  NULL    NULL
2012    OBJ1    NULL    255500  NULL
2021    OBJ2    NULL    309000  NULL

这就是我想要的

DATE    OBJ     BOUGHT  SOLD    DIFF
2009    OBJ1    235000  255500  20500
2012    OBJ2    255500  309000  53500
2021    OBJ3    305400  NULL    NULL

代码:

SELECT strftime('%Y', Op_Date) Year, Op_Obj OBJ ifnull(Op_TTBuy, 0) BOUGHT, ifnull(Op_TTSell, 0) SOLD, (Op_TTSell - Op_TTBuy) DIFF
FROM Operations 

我试了很多方法.. 任何帮助将不胜感激..

您可能需要按年份分组,大致如下:

SELECT strftime('%Y', Op_Date) Year, max(Op_Ob) OBJ
, sum(ifnull(Op_TTBuy, 0)) BOUGHT
, sum(ifnull(Op_TTSell, 0)) SOLD
, (sum(Op_TTSell) - sum(Op_TTBuy)) DIFF
FROM Operations 
group by strftime('%Y', Op_Date)
order by strftime('%Y', Op_Date)