将3 OUTER APPLY合并为1

时间:2018-01-09 14:31:28

标签: sql-server sql-server-2008-r2

我有一个选择查询,我在同一个表中使用3个OUTER APPLY语句,第一个条件对所有人都相同,其余的则不同。并且我用它来获得相同字段的SUM。有什么办法可以将所有这3个组合成1个吗?

以下是我到目前为止的完成情况:

OUTER APPLY
        (
            SELECT
                PaymentAmount = SUM(PaymentAmount)
                FROM PMT
                    WHERE InvoiceId = INV.InvoiceId
                    GROUP BY InvoiceId
        )P2
        OUTER APPLY
        (
            SELECT
                PaymentAmount = SUM(PaymentAmount)
                FROM PMT
                    WHERE InvoiceId = INV.InvoiceId
                        AND PaymentBatchID <= PB.PaymentBatchID
                        GROUP BY InvoiceId
        )P3
        OUTER APPLY
        (
            SELECT
                PaymentAmount = SUM(PaymentAmount)
                FROM PMT
                    WHERE InvoiceId = INV.InvoiceId
                        AND PaymentBatchID <= PB.PaymentBatchID
                        AND PaymentID <= Pay.PaymentID
                        GROUP BY InvoiceId
        )P4

表PMT具有以下列

InvoiceId - INT
PaymentId - INT
PaymentBatchId - INT
PaymentAmount - DECIMAL(10,2)

我尝试在同一个OUTER APPLY中使用Case,但是得到了以下错误

  

Msg 8124,Level 16,State 1,Line 134

     

指定了多个列   在包含外部引用的聚合表达式中。

     

如果正在聚合的表达式包含外部引用,那么   外部引用必须是表达式中引用的唯一列。

1 个答案:

答案 0 :(得分:0)

使用CASE ... WHEN作为条件

OUTER APPLY
(
        SELECT
               P2_PaymentAmount = SUM(x.PaymentAmount),
               P3_PaymentAmount = SUM(CASE WHEN x.PaymentBatchID <= PB.PaymentBatchID THEN x.PaymentAmount END),
               P4_PaymentAmount = SUM(CASE WHEN x.PaymentBatchID <= PB.PaymentBatchID
                                            AND x.PaymentID <= Pay.PaymentID THEN x.PaymentAmount END)
        FROM   
               PMT x
        WHERE  
               x.InvoiceId = INV.InvoiceId

) P234