mySql查询 – 减去结果值

我需要一些数学函数的帮助,

以下查询将导致每批2行,如下所示:

group | style | lot | section | q1 | q2 |q3  | q4  | ...

aaaaa | sssss | 123 | 111111  | 55 | 77 | 88 | 99 | ...

aaaaa | sssss | 123 | 222222  | 10 | 20 | 20 | 10 | ...

aaaaa | sssss | 321 | 111111  | 11 | 22 | 44 | 55 | ...

aaaaa | sssss | 321 | 222222  | 10 | 23 |33  | 10  | ...

每批次结果2差异部分代码(2行)

问题是:如何在colums q1 q2 q3 q4 q5 …的2段代码之间进行减法?

预期成绩:

group | style | lot | q1 | q2 |q3 | q4  | ...

aaaaa | sssss | 123 | 45 | 57 |68 | 89 | ...

aaaaa | sssss | 321 | 1  | -1 |11 | 45 | ...

查询到目前为止:

SELECT DISTINCT gp_style_gr.code_groupe, po_lot.num_style, po_lot_sp.Num_lot,
po_lot_sp.num_secti, po_lot_se.code_secti, po_lot.terminer, po_lot.date_livraison,
po_lot_sp.qte_1, po_lot_sp.qte_2, po_lot_sp.qte_3, po_lot_sp.qte_4, po_lot_sp.qte_5,
po_lot_sp.qte_6, po_lot_sp.qte_7, po_lot_sp.qte_8, po_lot_sp.qte_9, po_lot_sp.qte_10,
po_lot_sp.qte_11, po_lot_sp.qte_12, po_lot_sp.qte_13, po_lot_sp.qte_14, po_lot_sp.qte_15,
po_lot_sp.qte_16, po_lot_sp.qte_17, po_lot_sp.qte_18, po_lot_sp.qte_19, po_lot_sp.qte_20,
po_lot_sp.qte_21, po_lot_sp.qte_22, po_lot_sp.qte_23, po_lot_sp.qte_24, po_lot_sp.qte_25,
po_lot_sp.qte_26, po_lot_sp.qte_27, po_lot_sp.qte_28, po_lot_sp.qte_29, po_lot_sp.qte_30

FROM po_lot_sp

LEFT OUTER JOIN po_lot_se ON po_lot_se.num_lot = po_lot_sp.num_lot 
and po_lot_se.num_secti = po_lot_sp.num_secti

LEFT OUTER JOIN po_lot ON po_lot.num_lot = po_lot_sp.num_lot

LEFT OUTER JOIN gp_style_gr ON gp_style_gr.num_style = po_lot.num_style

WHERE
((gp_style_gr.code_groupe = 'INSTOCK') and (po_lot.terminer = '0') 
and (po_lot_se.code_secti = '01')) or ((gp_style_gr.code_groupe = 'INSTOCK') 
and (po_lot.terminer = '0') and (po_lot_se.code_secti = '09'))

ORDER BY gp_style_gr.code_groupe, po_lot.num_style, po_lot_sp.Num_lot, 
po_lot_sp.num_secti, po_lot_se.code_secti, po_lot.terminer, po_lot.date_livraison, 

谢谢 !

最佳答案 如果部分代码遵循某个模式,就像在示例中那样,那么您可以简单地将表连接到自身.

我假装你的表名为po_lot_sp,就像你的例子一样.

在以下查询中,我假设第二行具有更高的节号.这就是条件t1.section> t2.section.如果没有,请适当更改.如果节号不遵循模式,则完全忽略它.

SELECT t1.`group`, t1.style, t1.lot, t1.section,
  t2.q1 - t1.q1 q1, t2.q2 - t1.q2 q2, t2.q3 - t1.q3 q3, t2.q4 - t1.q4 q4
FROM t t1
JOIN t t2 ON t1.`group` = t2.`group` AND t1.style = t2.style AND
  t1.lot = t2.lot AND t1.section > t2.section

小提琴here.

点赞