1
USE exemple
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER  PROCEDURE [dbo].[SP_sum_inventory_byproduct_by_date_range] 
(
 @salesdate  datetime ,
 @upsalesdate1  datetime
 )
AS
BEGIN
SET NOCOUNT ON;

SELECT T1.ItemCode, SUM(T1.Quantity)
FROM
(
 SELECT T1.ItemCode, SUM(T1.Quantity)  
 FROM iiii T0  INNER JOIN ffff T1 ON T0.DocEntry = T1.DocEntry 
               INNER JOIN oooo t2 on t0.cardcode=t2.cardcode
 WHERE T0.DocDate >= @salesdate  and  T0.DocDate <= @upsalesdate 
 GROUP BY T1.ItemCode, T1.Dscription
 UNION
 SELECT T1.ItemCode , T1.Dscription , -SUM(T1.Quantity)
 FROM ORIN T0  INNER JOIN RIN1 T1 ON T0.DocEntry = T1.DocEntry 
               INNER JOIN ococ t2 on t0.cardcode=t2.cardcode
 WHERE T0.DocDate >= @salesdate and  T0.DocDate <= @upsalesdate 
 GROUP BY T1.ItemCode, T1.Dscription
 ) new
 GROUP BY [T1.ItemCode], [T1.Dscription] 
 ORDER BY itemcode 
END

这个查询在我的 SQL SERVER 2008 中工作(我删除了一些字段和真实的表名)。我尝试添加 ROWCOUNT 但没有成功,我收到错误。我应该如何在 SP 中做到这一点?

4

1 回答 1

0

有关使用 ROW_NUMBER 排名函数的更多详细信息,请参阅MSDN

ALTER  PROCEDURE [dbo].[SP_sum_inventory_byproduct_by_date_range] 
(
 @salesdate  datetime ,
 @upsalesdate1  datetime
 )
AS
BEGIN
SET NOCOUNT ON;

SELECT ROW_NUMBER() OVER(ORDER BY new.ItemCode) AS rn, new.ItemCode, SUM(new.Quantity) AS Quantity
FROM
(
 SELECT T1.ItemCode, SUM(T1.Quantity)  
 FROM iiii T0  INNER JOIN ffff T1 ON T0.DocEntry = T1.DocEntry 
               INNER JOIN oooo t2 on t0.cardcode=t2.cardcode
 WHERE T0.DocDate >= @salesdate  and  T0.DocDate <= @upsalesdate 
 GROUP BY T1.ItemCode, T1.Dscription
 UNION
 SELECT T1.ItemCode , T1.Dscription , -SUM(T1.Quantity)
 FROM ORIN T0  INNER JOIN RIN1 T1 ON T0.DocEntry = T1.DocEntry 
               INNER JOIN ococ t2 on t0.cardcode=t2.cardcode
 WHERE T0.DocDate >= @salesdate and  T0.DocDate <= @upsalesdate 
 GROUP BY T1.ItemCode, T1.Dscription
 ) new
 GROUP BY [new.ItemCode], [new.Dscription] 
 ORDER BY new.itemcode 
END
于 2013-08-29T12:32:24.007 回答