Search code examples
sqlsql-serversql-server-2008-r2window-functions

SQL Server 10.50 OVER PARTITION not recognized


I am trying to use OVER PARTITION in SQL Server 2008 R2 (v10.50.1600.1), but writing and executing it indicates an error near the ORDER, I tried to run this same query without modifications in SQL Server 2014 (v12.0.4100.1), but it works without problems, and in the SQL Server documentation I have not managed to find anything, I know there are other ways to simulate this process, but I would like to know if there is a more agile equivalence. Thank you

SELECT 
    e.ID, e.[date], 
    COUNT(*) OVER (PARTITION BY e.ID ORDER BY e.[date] DESC) AS ind
FROM 
    events e 
JOIN 
    Manager h ON h.ID = e.ID AND h.Active = 1 AND h.[Status] <> 30037 
WHERE 
    e.Iary IN (1, 2, 3) 
GROUP BY 
    e.ID, e.[date]

I get this error:

Msg 156, Level 15, State 1, Line 3
Incorrect syntax near the keyword 'ORDER'


Solution

  • The COUNT () is to keep a program account of that group, but already solve it, in 10.50 it is not compatible to use the ORDER BY with a COUNT (), which if it works and meets the objective in 12.0, changing the COUNT (* ) by ROW_NUMBER ()

    SELECT e.ID, e.[date], ROW_NUMBER() OVER (PARTITION BY e.ID ORDER BY e.[date] DESC) AS ind FROM events e JOIN Manager h ON h.ID = e.ID AND h.Active = 1 AND h.[Status] <> 30037 WHERE e.Iary IN (1, 2, 3) GROUP BY e.ID, e.[date]