查询包括来自两个表的总和并加入它们

时间:2017-12-06 17:19:14

标签: php sql jointable

我有两张桌子:

发票

id | name | invoice_number | invoice_total

资产负债表

id | name | invoice_number | amount_received | discount

我希望SQL查询按名称加入它们,并希望将invoice表中的invoice_total和amount_received的总和以及资产负债表中个别名称的折扣总和加起来。

结果应该是:

    name | sum(invoice_total) | sum(amount_received) | sum(discount)

非常感谢任何帮助。

3 个答案:

答案 0 :(得分:1)

假设您只需要完全匹配两个名称之间的故事您可以使用内部联接和分组

accesslevel_id = request.POST.get('accesslevel_id')

如果您还需要部分匹配,则可以使用左连接

 select table_1.name, sum(a.invoce_total), sum(AMOUNT_RECEIVED), sum(DISCOUNT)
 from invoice table_1
 inner join BALANCESHEET table_2 on table_1.name = table_2.name
 group by table_1.name

答案 1 :(得分:0)

可能需要稍微调整以考虑您的数据库结构,但请尝试以下方法:

select 
    sum(invoice.invoice_total) - sum(balancesheet.amount_received) - sum(balancesheet.discount) as total
from
    invoice
left join
    balancesheet
on
    invoice.name = balancesheet.name
group by
    invoice.name

答案 2 :(得分:0)

尝试

SELECT 
    `NAME`, 
    SUM(`INVOICE_TOTAL`) AS invTotal, 
    SUM(`AMOUNT_RECEIVED`) AS amtRxd, 
    SUM(`DISCOUNT`) AS totalDiscount 
    FROM `TABLE-1` T1 
        LEFT JOIN `TABLE-2` T2 
            ON T1.NAME=T2.NAME 
    GROUP BY T1.NAME