Sqlserver
 SQL >> Database >  >> RDS >> Sqlserver

Correggere "Incorrect Syntax Near 'order'" per SUM OVER in SQL Server 2012

I totali cumulativi con SUM() OVER (ORDER BY ...) non sono supportati prima di SQL Server 2012. Se vedi l'errore "Incorrect syntax near 'order'", probabilmente stai eseguendo SQL Server 2005 o 2008, oppure il tuo livello di compatibilità del database è impostato a 105 o inferiore (vedi qui).

Per quelle versioni precedenti, puoi ottenere lo stesso totale progressivo con outer apply:

select t.*, s.amount from @t t outer apply ( select sum(t2.amount) as amount from @t t2 where t2.cname = t.cname and t2.cid <= t.cid ) s;

Il outer apply correlato somma tutte le righe fino a quella corrente inclusa, riproducendo di fatto il totale cumulativo con finestra sui motori più vecchi.