SQL: Join 3 tables with count, addition, and more limits

SQL: Joining 3 tables with count, addition, and more restrictions

嘿伙计们,我真的被这个问题困住了。我想获得总量 (QT),即 Q1+Q2-Q3,每个 Q(n) 来自不同的 tables。

我有 3 table

tables:  STOCKURP    REPORTENABLEURP    RECHARGE
FK    :  code        code               accountid

每个 tables 的每个 CREDIT 都有不同数量的 QUANTITY,前两个 tables,STOCKURP 和 REPORTENABLEURP,已经存储了 QUANTITY,而对于 RECHARGE [=54= 】,我得先算了。

为了让你更容易理解,我将把这个东西分成几部分。

第 1 部分:2 数量

我想获取 2 table 中所有项目的 2 个数量的列表。 这是我的查询:

select stockurp.code as CODE, stockurp.credit, stockurp.quantity as Q1, reportenableurp.qty as Q2
from stockurp join reportenableurp 
on stockurp.code = reportenableurp.code and stockurp.credit = reportenableurp.credit 
where stockurp.date = '20150930' and reportenableurp.date = '2015-09-30'

有了这个,我明白了

CODE  CREDIT   Q1   Q2
12    15000    12   566
12    20000    24   341
43    15000    343  400
43    20000    12   65
46    50000    78   102

第 2 部分:计算 Q3

要获得第三个数量 (Q3),我必须计算每个 CREDIT 的 ACCOUNTID 出现了多少次。 我的查询是这样的:

select accountid, credit, count (recharge.credit) as Q3
from recharge
group by accountid, credit

结果是这样的:

ACCOUNTID   CREDIT   Q3
   12       15000    20
   12       20000    301
   45       15000    65
   67       50000    9

第三部分:QT总数量

QT = Q1 + Q2 - Q3

为此,我必须加入 3 个 table,但我似乎找不到办法做到这一点。我尝试了多种方法,例如:

select stockurp.code as CODE, stockurp.credit, Q1, Q2
from 
     (
    select count (recharge.credit) as Q3
    from recharge
    group by accountid, credit
    )
join 
    (
    select stockurp.quantity as Q1, reportenableurp.qty as Q2
    from stockurp join reportenableurp   
    on stockurp.code = reportenableurp.code and stockurp.credit = reportenableurp.credit 
    where stockurp.tanggal = '20150930' and reportenableurp.tanggal = '2015-09-30'
    )

on stockurp.code = reportenableurp.code

是的,我知道,那个查询很愚蠢,哈哈。我只是找不到正确的心态来获得解决方案。最终结果应该是这样的:

CODE  CREDIT   Q1   Q2   Q3   QT
12    15000    12   566  34   544
12    20000    24   341  124  241
43    15000    343  400  87   656
43    20000    12   65   50   27
46    50000    78   102  11   169

你们能帮我解决这个问题吗?提前致谢。

方法如下:

SELECT table1.CODE,table1.credit, Q1, Q2, Q3, Q1 + Q2 - Q3 total_result
FROM
(select stockurp.code as CODE, stockurp.credit, stockurp.quantity as Q1, reportenableurp.qty as Q2
from stockurp join reportenableurp 
on stockurp.code = reportenableurp.code and stockurp.credit = reportenableurp.credit 
where stockurp.date = '20150930' and reportenableurp.date = '2015-09-30')
table1
JOIN
(select accountid, credit, count (recharge.credit) as Q3
from recharge
group by accountid, credit) table2
ON table1.CODE=table2.accountid
AND table1.credit=table2.credit