我有两个表:一个用于发票,另一个用于付款:
tbl_Invoice
tbl_payment
欲望输出如下:
PSUM IPRICE
----------- ------------
312.00 1100.00
其中:
PSUM
是付款总额。
IPRICE
是该客户的Total_price总和。
我试过的查询是:
select
IsNull(sum(p.amt), 0) PSUM,
IsNull(sum(i.total_price), 0) IPRICE
from tbl_invoice i
left join tbl_payment p
on i.invoice_id = p.invoice_id
and i.client_id = p.client_id
where i.client_id = 5
group by i.invoice_id
order by i.invoice_id
但它输出错误:
PSUM IPRICE
----------- ------------
312.00 400.00
0.00 1000.00
答案 0 :(得分:1)
好像你想要这个。这给出了amt
和total_price
的总和,没有分组。您的版本分组由invoice_id
组成,区别在于:
select
IsNull(sum(p.amt), 0) PSUM,
IsNull(sum(distinct i.total_price), 0) IPRICE
from tbl_invoice i
left join tbl_payment p
on i.invoice_id = p.invoice_id
and i.client_id = p.client_id
where i.client_id = 5
你可以写这个的另一种方法是使用子查询:
select
IsNull(sum(p.amt), 0) PSUM,
IsNull(sum(i.total_price), 0) IPRICE
from
(
select sum(total_price) total_price, invoice_id, client_id
from tbl_invoice
group by invoice_id, client_id
) i
left join
(
select sum(amt) amt, invoice_id, client_id
from tbl_payment
group by invoice_id, client_id
) p
on i.invoice_id = p.invoice_id
and i.client_id = p.client_id
where i.client_id = 5
两者产生相同的结果:
| PSUM | IPRICE |
-----------------
| 312 | 1100 |