如何按查询计算组返回的实际记录数
例如
-- Exec SP_GET_ITEM_STOCK 0,10,NULL,'Charger'
ALTER PROCEDURE [dbo].[SP_GET_ITEM_STOCK]
@startRowIndex int ,
@pageSize int,
@ItemID bigint = null,
@ItemName varchar(250) = null
AS
BEGIN
DECLARE @SQL varchar(MAX)
DECLARE @SQLWHERE varchar(MAX)
SET @SQL = 'WITH DATA AS (
select
ROW_NUMBER() OVER (ORDER BY Item_ID) ''SNo'',
Item_ID,
Item_Name,
SUM(Inward) as Total_Purchase,
SUM(Outward) as Total_Sale,
(sum(Inward) - sum(outward))as Balance_Stock'
Set @SQLWHERE = ' from Item_Ledger_Details where Active = 1'
IF @ItemID IS NOT NULL and @ItemID <> ''
SET @SQLWHERE = @SQLWHERE + ' and Item_ID = ' + CONVERT(varchar,@ItemID) + ''
IF @ItemName IS NOT NULL and @ItemName <> ''
SET @SQLWHERE = @SQLWHERE + ' and Item_Name like ''%' + @ItemName + '%'''
SET @SQL = @SQL + @SQLWHERE + ' group by Item_ID,Item_Name) SELECT * FROM DATA WHERE SNo BETWEEN ' + CONVERT(Varchar,@startRowIndex) + ' AND ' + CONVERT(Varchar,@startRowIndex+@pageSize) + ' ORDER BY SNo'
EXEC(@SQL +';SELECT COUNT(*) ''Count'' '+ @SQLWHERE)
print(@SQL)
END
返回:
我需要计算上面的第一个结果记录,以得到第二个结果中的1 + 1 = 2,其中我得到计数= 48
答案 0 :(得分:1)
继续Anand回答。我刚刚修改了他的查询。下面的查询解决了我的答案。但我认为这个查询可能需要优化。
-- SP_GET_ITEM_STOCK 0,10,NULL,NULL
ALTER PROCEDURE [dbo].[SP_GET_ITEM_STOCK]
@startRowIndex int,
@pageSize int,
@ItemID bigint = null,
@ItemName varchar(250) = null
AS
BEGIN
Declare @Temp Table (
SNo bigint,
Item_ID bigint,
Item_Name varchar(max),
Total_Purchase money,
Total_Sale money,
Balance_Stock money
);
WITH DATA AS (
select
ROW_NUMBER() OVER (ORDER BY Item_ID) as SNo,
Item_ID,
Item_Name,
SUM(Inward) as Total_Purchase,
SUM(Outward) as Total_Sale,
(sum(Inward) - sum(outward))as Balance_Stock
from Item_Ledger_Details
where Active = 1
and (coalesce(@ItemID, '') = '' or Item_ID = CONVERT(varchar,@ItemID))
and ( coalesce(@ItemName, '') = '' or Item_Name like '%' + @ItemName + '%')
group by Item_ID,
Item_Name
)
insert into @Temp
SELECT *
FROM DATA
WHERE SNo BETWEEN @startRowIndex AND @startRowIndex+@pageSize
ORDER BY SNo
select * from @temp
SELECT COUNT(*) as Count from @temp
END
答案 1 :(得分:0)
在那里,我把它清理干净了:
ALTER PROCEDURE [dbo].[SP_GET_ITEM_STOCK]
@startRowIndex int,
@pageSize int,
@ItemID bigint = null,
@ItemName varchar(250) = null
AS
BEGIN
;WITH DATA AS (
select
ROW_NUMBER() OVER (ORDER BY Item_ID) as SNo,
Item_ID,
Item_Name,
SUM(Inward) as Total_Purchase,
SUM(Outward) as Total_Sale,
(sum(Inward) - sum(outward))as Balance_Stock
from Item_Ledger_Details
where Active = 1
and (coalesce(@ItemID, '') = '' or Item_ID = CONVERT(varchar,@ItemID))
and ( coalesce(@ItemName, '') = '' or Item_Name like '%' + @ItemName + '%')
group by Item_ID,
Item_Name
)
SELECT *
FROM DATA
WHERE SNo BETWEEN @startRowIndex AND @startRowIndex+@pageSize
ORDER BY SNo
SELECT COUNT(*) as Count
from DATA
END