I have bill data from two sources. I want to join them to be able to see where there is a record in one set that is not in the other and vice versa. This query does what I want but I feel like it could be written more elegantly? I only want one field for the account number and bill date (M and Y), and then separate fields for the the charges in each source.
DECLARE @BillDate datetime ='2/1/2016'
SELECT ACCT_NO = COALESCE(BPFACCT,CSTACCT) ,
BillDate = COALESCE(BPFBillDate,CSTBillDate) ,
BPFCharge ,
CSTCharge ,
Delta = ROUND(COALESCE(BPFBill.BPFCharge,0)-COALESCE(CSTBill.CSTCharge,0),2)
FROM
(
SELECT
BPFACCT = acct_no ,
BPFBillDate = cast(billdate as date) ,
BPFCharge = SUM(charge)
FROM
cisbill b
JOIN
cisbilldetail bd ON b.billid=bd.billid
WHERE
billdate>=@BillDate
AND
billdate<DATEADD(MONTH, 1, @BillDate)
GROUP BY
acct_no, billdate
) BPFBill
FULL OUTER JOIN
(
SELECT CSTACCT = acct_no ,
CSTBillDate = cast(bill_date as date) ,
CSTCharge = SUM(new_charges)
FROM
cst_bill
WHERE
bill_date>=@BillDate
AND
bill_date<DATEADD(MONTH, 1, @BillDate)
GROUP BY
acct_no, bill_date
) CSTBill
ON BPFBill.BPFACCT=CSTBill.CSTACCT
AND
BPFBill.BPFBillDate=CSTBill.CSTBillDate
Appreciate any feedback!