简体   繁体   中英

Solution to not being able to use ORDER BY in Partition in SQL Server 2008

I have the following query which works great on SQL Server 2012:

   SELECT Name, 
     WeekNumber,
     SUM(NumberOfSecondsWorked) AS totalDaily,
     StartTime,
     EndTime,
     SUM(SUM(NumberOfSecondsWorked)) OVER (PARTITION BY WeekNumber ORDER BY EndTime) AS totalWeekly 
   FROM #temp AS T1

But unfortunately I get the following error when running this query on a SQL Server 2008 DB:

Incorrect syntax near 'order'.

My desired outcome of the above query is to add the NumberOfSecondsWorked by Day for each week. Here is my desired output:

在此处输入图片说明

But without the ORDER BY, I just get a total for each week without the increment by day:

在此处输入图片说明

Anybody know how to run the above query in SQL Server 2008? Or a mechanism to get the same result? Thanks!

SQL Server 2008 doesn't support cumulative sums. My recommendation is to upgrade to a supported version of SQL Server.

That said, you can implement this using a correlated subquery or lateral join (ie apply ):

SELECT t.*,
       (SELECT SUM(t2.totalDaily)
        FROM #temp t2
        WHERE t2.WeekNumber = t.WeekNumber AND
              t2.EndTime <= t.EndTime
       ) as running_weekly
FROM #temp t2

I suggest you to read the following article : https://dba.stackexchange.com/questions/47116/in-microsoft-sql-server-2008-syntax-generates-the-error-the-parallel-data-ware

It explains that what you want to do is not supported until SQL2012. You can use the workaround suggested by the collegue but the best solution is to migrate to sql server version that supports what you want to do. Bye, Simone

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM