我怎样才能使用OVER和ORDER BY

时间:2012-04-05 12:35:23

标签: sql sql-server sum sql-order-by window-functions

我无法理解这段代码的错误。

CODE:

SELECT
    CariID, HesapID, BTrh, BCinsiID, BNo, Acklm, VdTrh, mTrh, BorcT, AlacakT, 
    SUM(BorcT) OVER (PARTITION BY CariID, HesapID ORDER BY BTrh, BNo, mTrh) AS TopBorcT, 
    SUM(AlacakT) OVER (PARTITION BY CariID, HesapID ORDER BY BTrh, BNo, mTrh ) AS TopAlacakT
FROM
    tCariH

错误:

  

Msg 102,Level 15,State 1,Line 3

     

'order'附近的语法不正确。

3 个答案:

答案 0 :(得分:2)

使用SUMyou don't use ORDER BY in the OVER clause这样的聚合函数 - 您只需要使用PARTITION函数。 ORDER用于排名函数:

  

可能不支持与OVER子句一起使用的排名,聚合或分析函数,<ORDER BY clause>和/或<ROWS and RANGE clause>

只需修改即可删除两个聚合中的ORDER,您应该没问题。

答案 1 :(得分:1)

显然,SQL Server 2008不支持此功能,但SQL Server 2012支持

How to use partition by and order by in over function?

试试这个工具,您可以看到原因: http://sqlfiddle.com/#!6/5303f/1

答案 2 :(得分:0)

ID      AccountID       Quantity
1          1               10           Sum = 10
2          1               5                = 10 + 5 = 15
3          1               2                = 10 + 5 + 2 = 17
4          2               7                = 7
5          2               3                = 7 + 3 = 10  

SELECT ID, AccountID, Quantity, 
       SUM(Quantity) OVER (PARTITION BY AccountID ) AS TopBorcT, 
FROM tCariH