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中工作(我删除了一些字段和实际的表名)。 我试图增加行数并且我没有成功,我得到错误。我在SP中怎么做这个?
答案 0 :(得分: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