我正在尝试使用OVER
子句返回一行。我的代码如下:
SELECT SUM(Price) OVER (ORDER BY [InvoiceID] ROWS UNBOUNDED PRECEDING)
FROM dbo.Sales
WHERE InvoiceID = 3427
我想回来:
InvoiceID Price
3427 15.00
相反,返回的是:
InvoiceID Price
3427 5.00
3427 10.00
3427 15.00
我如何获得一行?
答案 0 :(得分:1)
不确定您使用OVER()
子句的原因。似乎你只需要:
SELECT InvoiceID, Price = SUM(Price)
FROM dbo.Sales
WHERE InvoiceID = 3427 -- maybe you want more than just this one?
-- if so, leave out the WHERE clause
GROUP BY InvoiceID;
答案 1 :(得分:0)
实际上,OVER子句中的窗口规范有三个主要部分:分区,排序和框架。窗口框架子句(ROWS BETWEEN AND)从两个指定分隔符之间的窗口分区过滤行的帧或子集。在您的查询中,未正确指定帧,它应该在分区的开头(即UNBOUNDED PRECEDING)和当前行(CURRENT ROW)之间。以下查询应该有所帮助:
SELECT SUM(Price) OVER (ORDER BY [InvoiceID] ROWS BETWEEN UNBOUNDED PRECEDING
AND CURRENT ROW)
FROM dbo.Sales
WHERE InvoiceID = 3427