我需要帮助。我正在使用MS Access DB
TIA
我想结合这两个SQL查询来获得单个输出。
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
结果:
001 1/1/1970 arvin 109500
查询#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
结果:
001 105000
我希望结果会像这样
001 1/1/1970 arvin 109500 105000
TIA
答案 0 :(得分:0)
试试这个解决方案:
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
如果ID没有pamount
。然后在Second SubQuery中使用LEFT JOIN
:
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
答案 1 :(得分:0)
我认为您只需要添加其他joins
与表格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
我怀疑上面的内容不会给你想要的东西,但第二个版本可能会有用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