简体   繁体   English

SQL Server 2008使用SUM()OVER(ORDER BY ...)

[英]SQL Server 2008 using SUM() OVER(ORDER BY…)

I am trying to use a CTE and CROSS JOIN the result set. 我正在尝试使用CTE和CROSS JOIN结果集。 I want to sum up the 4 rows leading up to the current row. 我想总结一下导致当前行的4行。 The example online I found does not use a CTE, only a newly created table ( http://sqlandme.com/2011/08/17/sql-server-denali-over-rows-range/ ). 我找到的在线示例不使用CTE,只使用新创建的表( http://sqlandme.com/2011/08/17/sql-server-denali-over-rows-range/ )。 The syntax should work, but I get an error saying "Incorrect syntax near 'ROWS'". 语法应该有效,但是我收到一条错误,说“'ROWS'附近的语法不正确”。

An Example output would be this using the following statement: SUM(y) OVER(ORDER BY x ROWS 4 PRECEDING) sum 使用以下语句的示例输出:SUM(y)OVER(ORDER BY x ROWS 4 PRECEDING)sum

XY SUM XY SUM


     1          7     0     No prev rows, so sum is 0
     2          1     7     Sum   = 7 
     3          2     8           = 1 + 7
     4          5     10          = 2 + 1 + 7
     5          7     15          = 5 + 2 + 1 + 7
     6         34     15          = 7 + 5 + 2 + 1
     7         32     48          = 34 + 7 + 5 + 2

Does anyone have any suggestion on what is incorrect with the query? 有没有人对查询的错误有任何建议? Thanks in advance. 提前致谢。

with quarterResults as (
      <subquery in here>
)

--COLUMN1: String
--COLUMN2: Date
--COLUMN3: Date
--COLUMN4: Double
select a.TIC, a.DATADATE, a.EFFDATE, SUM(b.valuei) OVER (ORDER BY a.TIC, a.DATADATE, a.EFFDATE ROWS 4 PRECEDING) AS [SUM]
from quarterResults a
cross join quarterResults b
where a.datadate > b.datadate
group by a.tic, a.datadate, a.EFFDATE, a.valuei
order by a.TIC, a.datadate

The documentation you found for ROWS/RANGE is not for SQL Server 2008 - it's for a future version of SQL Server. 您找到的ROWS / RANGE文档不适用于SQL Server 2008 - 它适用于SQL Server的未来版本。

To accomplish your query in SQL 2008, one approach would be similar to: 要在SQL 2008中完成查询,一种方法类似于:

SELECT a.TIC, a.datadate, a.effdate, x.s
FROM quarterResults a
    CROSS APPLY (   SELECT ISNULL(SUM(v), 0)
                    FROM (  SELECT TOP(4) b.valuei
                            FROM quarterResults b
                            WHERE b.datadate < a.datadate
                            ORDER BY b.datadate DESC ) x(v)
                ) x(s)
ORDER BY a.TIC, a.datadate

Note that this is potentially an expensive query. 请注意,这可能是一个昂贵的查询。 The use of the OVER expression with ROWS would probably be more efficient but, again, it is not available in SQL Server 2008. 将OVER表达式与ROWS一起使用可能会更有效,但同样,它在SQL Server 2008中不可用。

You tagged SQL Server 2008. 您标记了SQL Server 2008。

The syntax isn't ready until next release SQL Server 2012 aka Denali 在下一版本SQL Server 2012又名Denali之前,语法尚未就绪

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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