我想在一个查询中从两个不同的表中的一个地方创建数据我必须使用数据透视表而在另一个查询中我想要总结相同客户名称即将到来的账单总数来自表1
表1查询
SELECT Cname
,Advance
,Bill
,Refund
FROM (
SELECT cname
,r.Amount
,R.PaymentType
FROM ReceiptDetails r
) AS sourcetable
PIVOT(
SUM(Amount)FOR PaymentType IN ([Advance] ,[Bill] ,[Refund])
) AS PivotTable
表2查询
SELECT Cname
,SUM(cb.totalandvat)
FROM Customer_Bill
Cname是表
中的公共字段基本上我想生成客户的会费列表,所以从表一(Recipt Details)名称,(总和)预付款和其他付款以及第二张表(账单明细)总金额来自多个账单
答案 0 :(得分:0)
只需执行完全外部联接,就像这样:
SELECT
CName = coalesce(payment.cname,bill.cname)
,bill = coalesce(bill.Amount)
,Advance = coalesce(payment.Advance,0)
,Bill = coalesce(payment.Bill ,0)
,Refund = coalesce(payment.Refund ,0)
FROM (
SELECT Cname
,Advance
,Bill
,Refund
FROM (
SELECT cname
,r.Amount
,R.PaymentType
FROM ReceiptDetails r
) AS sourcetable
PIVOT(
SUM(Amount)FOR PaymentType IN ([Advance] ,[Bill] ,[Refund])
) AS PivotTable
) Payment
full outer join (
SELECT Cname
,SUM(cb.totalandvat) AS Amount
FROM Customer_Bill
) bill
ON payment.cname = bill.cname