1

我有一个看起来像这样的表:

InvoiceNumber   AccountNumber   SumAmount
---------------------------------------------
1765            4150            20687.5000
1765            1100            20687.5000
1766            4150            41895.0000
1766            7730               20.0000
1797            4150                0.0000
1797            7730               20.0000
1797            1100             6652.3400
1797            4990             6652.3400

它是由这个查询生成的:

SELECT InvoiceNumber
    ,AccountNumber
    ,SUM(Amount) AS SumAmount
FROM vINVOICE_TABLE
GROUP BY InvoiceNumber
    ,AccountNumber
ORDER BY InvoiceNumber

我想应用这个逻辑:

  • 如果SumAmount_Account 1 > SumAmount_Account2,取Account1
  • 如果SumAmount_Account 1 == SumAmount_Account2,取较大的帐户

所以,结果应该是这样的:

InvoiceNumber   AccountNumber
---------------------------------
1765            4150
1766            4150
1797            4990
4

1 回答 1

3

这可以做到。

SELECT InvoiceNumber, AccountNumber
FROM 
(
    SELECT  
        Row_Number() OVER(
            Partition BY InvoiceNumber  
            ORDER BY SUM(Amount) DESC, AccountNumber DESC
        ) rowNumber,
        InvoiceNumber,
        AccountNumber
    FROM vINVOICE_TABLE
    GROUP BY InvoiceNumber, AccountNumber 
)inv
WHERE rowNumber = 1
于 2012-11-16T17:32:30.447 回答