无法从Left Join Where和group by找出预期结果

时间:2019-10-18 17:09:14

标签: mysql sql

我有两个应收帐款表&

表:应收款

tranId  roll     month         amount
 1      1111    October-2019    10
 2      1112    October-2019    10
 3      1113    October-2019    10
 4      1114    October-2019    10
 5      1115    October-2019    10

表格:接收

tranId   roll       month       amount
1       1111    October-2019    10
2       1111    September-2019  10
3       1113    October-2019    10
4       1114    October-2019    10
5       1115    October-2019    10
6       1116    October-2019    10
7       1117    October-2019    10
8       1118    October-2019    10
9       1119    October-2019    10
10      1120    October-2019    10

在两个表月份列中都是字符串,并且表接收卷+月份列是唯一的。我想从诸如此类的表格中创建一个学生的应收账款和收款报表(其中roll = 1111)。

预期结果:

month           rcvamount   rcvvmonth      rcvvamount
---------------------------------------------------------
October-2019       10       October-2019    10
---------------------------------------------------------
September-2019     10           -                -

我的查询是:

SELECT receive.month, sum(receive.amount) AS rcvamount, receivable.month AS rcvvmonth,
       receivable.amount AS rcvvamount
FROM receive
    LEFT JOIN receivable ON receive.month = receivable.month
WHERE receive.roll = 1111
GROUP BY receive.month

结果是:

month           rcvamount   rcvvmonth      rcvvamount
----------------|-------|----------------------------------
October-2019    |   50  |       October-2019    10
----------------|-------|----------------------------------
September-2019     10           -                -

2019年10月的revmount应该是接收表中的10。

1 个答案:

答案 0 :(得分:1)

您可以在加入之前 进行汇总。或使用union all进行汇总:

SELECT month, SUM(ramount) AS rcvamount, 
       SUM(raamount) AS rcvvamount
FROM ((SELECT month, amount as ramount, null as raamount
       FROM receive
       WHERE roll = 1111
      ) UNION ALL
      (SELECT month, NULL as ramount, amount as raamount
       FROM receiveable
       WHERE roll = 1111
      )
     ) r
GROUP BY month; 

UNION ALL的一个不错的功能是它可以处理任一表中的丢失数据。

相关问题
最新问题