对两个列进行求和,其中,组和

时间:2019-02-12 16:16:55

标签: mysql sql

我有两个桌子。一个叫Documents,另一个叫Payments我希望能够按Group Documents.InvoiceNumber的所有行,而我希望能够SUM的所有行来自Payments的记录与其Document.InvoiceNumber具有相同的Mode

例如在Documents中,我有以下行:

---------------------------------
|ID      |Acct  |InvoiceNumber  |
---------------------------------
|27509   |68213 |0000024383     |
---------------------------------
|27508   |68396 |0000024383     |
---------------------------------
|27507   |68418 |0000024382     |
---------------------------------

Payments中,我具有以下行:

------------------------------------
|ID     |Acct  |OperType|Qtty |Mode|
------------------------------------
|156396 |68396 |2       |43.89|1   |
------------------------------------
|156389 |68418 |2       |36.96|1   |
------------------------------------
|156314 |68418 |2       |36.96|-1  |
------------------------------------
|156265 |68213 |2       |52.25|1   |
------------------------------------
|156264 |68396 |2       |43.89|-1  |
------------------------------------
|155895 |68213 |2       |52.25|-1  |
------------------------------------

我希望能够检查是否

  

InvoiceNumber-> Payments.Mode = -1-> SUM(Qtty)等于InvoiceNumber-> Payments.Mode = 1-> SUM(Qtty)

例如:

Invoice Number = 0000024383 | Mode = -1 | Qtty = 96.14
Invoice Number = 0000024383 | Mode =  1 | Qtty = 96.14

我希望能够在mysql语句中检入这两个是否相同,并且我希望仅输出不相同的记录。

1 个答案:

答案 0 :(得分:1)

如果我正确地遵循了您的说明,那么您应该可以使用条件聚集来解决此问题:

SELECT 
    d.invoicenumber,
    SUM(CASE WHEN p.mode = -1 THEN p.qtty ELSE 0 END) qtty_minus1,
    SUM(CASE WHEN p.mode = 1 THEN p.qtty ELSE 0 END) qtty1
FROM 
    Documents d
    INNER JOIN Payments p ON p.acct = d.acct
GROUP BY 
    d.invoicenumber
HAVING 
    SUM(CASE WHEN p.mode = -1 THEN p.qtty ELSE 0 END) 
    <> SUM(CASE WHEN p.mode = 1 THEN p.qtty ELSE 0 END)

查询按发票编号汇总记录,然后将模式为-1的记录总数与模式为1的记录总数进行比较。 HAVING子句可确保结果中仅显示总量不同的发票编号。

请参见 this DB Fiddle demo :由于其中没有违规记录,我不得不更改您的示例数据。

| invoicenumber | qtty_minus1 | qtty1 |
| ------------- | ----------- | ----- |
| 0000024383    | 96.13       | 96.14 |