简体   繁体   中英

2 Sums from 3 tables MS Access SQL query

I want help on this. I'm using MS Access DB

TIA

I want to combine these 2 SQL queries to get a single output.

select a.salesid, salesdate, customername, sum(qty*price)  
from tblsales a 
inner join tblsales_details b on b.salesid = a.salesid 
where customername like '%arvin%' 
group by a.salesid, salesdate, customername

Result:

001 1/1/1970 arvin 109500

Query #2:

select a.salesid, sum(b.pamount) as payment 
from tblsales a 
inner join tblpayments b on b.salesid = a.salesid 
where customername like '%arvin%' 
group by a.salesid

Result:

001 105000

I want the result will be like this

001 1/1/1970 arvin 109500 105000

TIA

Try this solution:

SELECT x.salesid, x.salesdate, x.customername, x.amount, y.payment
FROM (
      select a.salesid, salesdate, customername, sum(qty*price) AS amount  
      from tblsales a 
      inner join tblsales_details b 
      on b.salesid = a.salesid 
      where customername like '%arvin%' 
      group by a.salesid, salesdate, customername
     ) AS x
INNER JOIN (
            select a.salesid, sum(b.pamount) as payment 
            from tblsales a 
            inner join tblpayments b 
            on b.salesid = a.salesid 
            where customername like '%arvin%' 
            group by a.salesid
           ) AS y
ON x.salesid = y.salesid

If there is no pamount for an id. Then use LEFT JOIN like this in Second SubQuery:

select a.salesid, sum(IFF(b.pamount IS NULL, 0, b.pamount)) as payment 
from tblsales a 
LEFT JOIN tblpayments b 
on b.salesid = a.salesid 
where customername like '%arvin%' 
group by a.salesid

I think you would just need to add other joins with table tblpayments

select a.salesid, a.salesdate, a.customername, 
       sum(b.qty*b.price) as TotalPrice, sum(p.pamount) as payment 
from tblsales a 
inner join tblsales_details b on b.salesid = a.salesid 
inner join tblpayments p on p.salesid = a.salesid -- you might be need left join
where a.customername like '%arvin%' 
group by a.salesid, a.salesdate, a.customername

I suspect that the above would not give what you want, but the second version might helpful by using a subquery

select a.salesid, a.salesdate, a.customername, sum(b.qty*b.price) as TotalPrice, 
      (select IIF(SUM(pamount) IS NULL, 0, SUM(pamount)) from tblpayments where salesid  = a.salesid) as payment 
from tblsales a 
inner join tblsales_details b on b.salesid = a.salesid 
where a.customername like '%arvin%' 
group by a.salesid, a.salesdate, a.customername

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM