这个Full Outer Join查询可以简化吗?

时间:2016-05-06 18:09:56

标签: sql sql-server tsql full-outer-join

我有来自两个来源的账单数据。我想加入他们,以便能够看到一组中的记录在另一组中没有,反之亦然。这个查询做了我想要的但我觉得它可以写得更优雅?我只需要一个字段用于帐号和帐单日期(M和Y),然后为每个来源中的费用分别填写字段。

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

感谢任何反馈!

1 个答案:

答案 0 :(得分:-1)

我觉得这会给你一个更准确的结果..

DECLARE @StartDate DATETIME = '2/1/2016',
        @EndDate DATETIME
SET     @EndDate = DATEADD(MONTH, 1, @BillDate)

SELECT  ACCT_NO,
        MM,
        YY,
        BPFCharge = SUM(BPFCharge),
        CSTCharge = SUM(CSTCharge)
FROM 
(
    SELECT  acct_no,
            MM = MONTH(billdate),
            YY = YEAR(billdate),
            BPFCharge = charge
            CSTCharge = 0.00
    FROM    cisbill b
            JOIN cisbilldetail bd ON b.billid = bd.billid
    WHERE   billdate >= @StartDate
            AND billdate < @EndDate
    UNION ALL
    SELECT  acct_no,
            MONTH(bill_date),
            YEAR(Bill_date),
            0.00,
            new_charges
    FROM    cst_bill
    WHERE   bill_date >= @StartDate
            AND bill_date < @EndDate
) t
GROUP BY ACCT_NO,
        MM,
        YY