Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use OVER and ORDER BY

I can't understand this code's bug.

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

ERROR:

Msg 102, Level 15, State 1, Line 3

Incorrect syntax near 'order'.

like image 600
serkan Avatar asked Apr 05 '12 12:04

serkan


People also ask

What is the use of ORDER BY in an over clause?

Window functions might have the following arguments in their OVER clause: PARTITION BY that divides the query result set into partitions. ORDER BY that defines the logical order of the rows within each partition of the result set.

Can having be used with ORDER BY?

HAVING Clause returns the grouped records which match the given condition. You can also sort the grouped records using ORDER BY.

How do you use GROUP BY in over?

You need to nest the sums: SELECT Year, Country, SUM([Total Sales]), SUM(SUM([Total Sales])) OVER (PARTITION BY Year) FROM Table GROUP BY Country, Year; This syntax is a little funky the first time you see it. But, the window function is evaluated after the GROUP BY .

What is the use of over partition by in SQL?

The SQL PARTITION BY expression is a subclause of the OVER clause, which is used in almost all invocations of window functions like AVG() , MAX() , and RANK() . As many readers probably know, window functions operate on window frames which are sets of rows that can be different for each record in the query result.


1 Answers

With an aggregate function like SUM, you don't use ORDER BY in the OVER clause - you only need to use the PARTITION function. The ORDER is used for ranking functions:

Depending on the ranking, aggregate, or analytic function used with the OVER clause, <ORDER BY clause> and/or the <ROWS and RANGE clause> may not be supported.

Just modify to remove the ORDER in both your aggregates and you should be fine.

like image 120
JNK Avatar answered Oct 13 '22 01:10

JNK