SQL Server 2008中的给定错误导致分区过度
我有以下疑问:SQL Server 2008中的给定错误导致分区过度,sql,sql-server,window-functions,Sql,Sql Server,Window Functions,我有以下疑问: SELECT *, SUM(BalanceQty) OVER (PARTITION BY Item_Code ORDER BY [Date]) FROM (SELECT Date, Item_Code, SUM(In_Quantity) AS In_Quantity, SUM(Issue_Quantity) AS Issue_Quantity, (SUM(In_Quanti
SELECT
*,
SUM(BalanceQty) OVER (PARTITION BY Item_Code ORDER BY [Date])
FROM
(SELECT
Date, Item_Code,
SUM(In_Quantity) AS In_Quantity,
SUM(Issue_Quantity) AS Issue_Quantity,
(SUM(In_Quantity) - SUM(issue_Quantity)) AS BalanceQty
FROM
(SELECT
tbl_add_product.Date as Date,
tbl_add_product.Item_Code,
tbl_add_product.In_Quantity,
0 as Issue_Quantity
FROM
tbl_add_product
WHERE
Item_Code = 'pen'
UNION ALL
SELECT
tbl_issue_product.Date as Date,
tbl_issue_product.Item_Code,
0 as In_Quantity,
Issue_Quantity
FROM
tbl_issue_product
WHERE
Item_Code = 'pen') X
GROUP BY
Item_Code, Date) o
它在SQL Server 2012中工作正常,但在SQL Server 2008中导致错误。请建议解决方案。您需要在SQL SERVER 2008中更改数据库兼容性模式,右键单击数据库选择属性,单击选项更改兼容性级别:
如果您想要一个同时适用于两者的解决方案,请尝试以下方法:
;WITH cte
AS (SELECT Date,
Item_Code,
Sum(In_Quantity) AS In_Quantity,
Sum(Issue_Quantity) AS Issue_Quantity,
( Sum(In_Quantity) - Sum(issue_Quantity) ) AS BalanceQty
FROM (SELECT tbl_add_product.Date AS Date,
tbl_add_product.Item_Code,
tbl_add_product.In_Quantity,
0 AS Issue_Quantity
FROM tbl_add_product
WHERE Item_Code = 'pen'
UNION ALL
SELECT tbl_issue_product.Date AS Date,
tbl_issue_product.Item_Code,
0 AS In_Quantity,
Issue_Quantity
FROM tbl_issue_product
WHERE Item_Code = 'pen') X
GROUP BY Item_Code,Date)
SELECT *,(select SUM(BalanceQty) from cte c2 where c2.Date <=c1.Date)
FROM cte c1
可以使用外部应用或相关子查询执行此操作:
with t as (<your big subquery here>)
select t.*
(select sum(BalanceQty)
from t t2
where t2.Item_Code = t.Item_Code and t2.[Date] <= t.[Date]
) as RunningBalance
from t;
编辑:
如果要将结果限制为一项,可以将项_Code='pen'添加到外部查询。在sql server 2008中,支持按分区,但不支持按顺序。解决方案是什么?解决方案:使用2012-您已经说过它可以工作,尽管提到了一个解决方案,包含实际的错误消息可能有助于将来的搜索。它在SQL Server 2008中会导致什么错误?我不确定,但如果是SQL Server 2008 smss,则不会在该组合中显示SQL Server 2012。2008下当前选择的值是什么您可以删除项目代码条件,因为根据给定的查询,所有行都将具有相同的项目代码。