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 @BillMonth int=2, @BillYear int=2016
SELECT ACCT_NO = COALESCE(BPFACCT,CSTACCT) ,
MM = COALESCE(BPFMM,CSTMM) ,
YY = COALESCE(BPFYY,CSTYY) ,
BPFCharge ,
CSTCharge ,
Delta = ROUND(COALESCE(BPFBill.BPFCharge,0)-COALESCE(CSTBill.CSTCharge,0),2)
FROM
(
SELECT
BPFACCT = acct_no ,
BPFMM = MONTH(billdate) ,
BPFYY = YEAR(billdate) ,
BPFCharge = SUM(charge)
FROM
cisbill b
JOIN
cisbilldetail bd ON b.billid=bd.billid
WHERE
MONTH(billdate)=@BillMonth
AND
YEAR(billdate)=@BillYear
GROUP BY
acct_no, billdate
) BPFBill
FULL OUTER JOIN
(
SELECT CSTACCT = acct_no ,
CSTMM = MONTH(bill_date) ,
CSTYY = YEAR(Bill_date) ,
CSTCharge = SUM(new_charges)
FROM
cst_bill
WHERE
MONTH(bill_date)=@BillMonth
AND
YEAR(bill_date)=@BillYear
GROUP BY
acct_no, bill_date
) CSTBill
ON BPFBill.BPFACCT=CSTBill.CSTACCT
AND
BPFBill.BPFMM=CSTBill.CSTMM
AND
BPFBill.BPFYY=CSTBill.CSTYY
Appreciate any feedback!
