MS SQL分页和分组

时间:2017-03-10 01:36:27

标签: sql-server pagination grouping row-number

我需要帮助,因为我正在努力解决如何浏览和限制每个页面一次只显示一个进程的问题。我尝试了很多东西,我的大脑被炒了。救命........ 所以如果@PageNum = 1 and @Pagesize = 10并且第一个进程有7行;第一页将显示第一个进程的7行(正是我想要的)。 现在,如果用户选择@PageNum = 2 and @Pagesize is 10而第二个进程有11.我希望它显示下一个进程的前10个。

目前它只显示第二个过程的最后8个。

我简化了SQL以删除商业信息,然后只显示我正在处理的内容列表:

/*
notes:
Parameters passed in are @PageNum and  @PageSize
@PageNum is which page they user goes to 
@PageSize is the max number of rows to show
*/

DECLARE @StartRow int, @EndRow int
SET @StartRow = (@PageNum -1) * @PageSize +1;
SET @EndRow = @PageNum * @PageSize;

WITH ProcessestoPageThru AS
(Select  Name, 
       ProcessId,
       ROW_NUMBER() OVER(ORDER BY Name, ProcessId, ) as RowNo,
       COUNT(Name) OVER() as RowCnt
from a whole bunch of tables
where a whole bunch of criteria
)

  SELECT  * INTO #tmp_ProcessestoPageThru 
  From ProcessestoPageThru 
  Where RowNo BETWEEN @StartRow AND @EndRow

  Declare @ProcessID int
  --Get the top ProcessID, We are only going to display one Process at a     time
  Select Top 1 @ProcessID = ProcessId
  From #tmp_ProcessestoPageThru 

  Select *
  from #tmp_ProcessestoPageThru
  Where ProcessId = @ProcessId 

请参阅附带的示例: Example enter image description here

2 个答案:

答案 0 :(得分:0)

您还需要在PARTITION BY上执行ProcessId以按列值显示结果。以下是可以帮助您完成此操作的代码。

;WITH ProcessestoPageThru AS
(
Select Name, 
       ProcessId,
       ROW_NUMBER() OVER( PARTITION BY ProcessId ORDER BY Name, ProcessId ) as RowNo,
       COUNT(Name) OVER() as RowCnt
FROM processes
)
SELECT  Name,
        ProcessId,
        RowNo,
        RowCnt
From ProcessestoPageThru 
Where RowNo BETWEEN @StartRow AND @EndRow
AND ProcessId = @ProcessID

答案 1 :(得分:0)

尝试使用其他样本数据。

如果真实数据速度很慢,请告诉我详情。

i)除了其他搜索条件之外,你只传递@ Pageinde,@ Pagesize等参数。

ii)TotalPage是您获得的页数,并且必须按照您的页面进行操作。忘记旧的计算。

iii)不需要rowcnt。

declare @Pageindex int=1
declare @Pagesize int=10



declare @t table(processid int, rowcnt int)
insert into @t values(1,345),(1,345),(1,345),(1,345),(1,345),(1,345),(1,345)
,(1,345),(1,345),(1,345),(1,345),(1,345)
,(2,345),(2,345),(2,345),(2,345),(2,345),(2,345),(2,345),(2,345)
,(2,345),(2,345),(2,345),(3,345),(3,345)


;with CTE as
(
select * 
,DENSE_RANK()over(order by processid) rownum
--,ROW_NUMBER()over(partition by processid order by processid) rownum1
,ROW_NUMBER()over(order by processid) rownum2
from @t
)
,CTE1 AS(
select *,
case when (rownum2/cast(@Pagesize as FLOAT))=1 then (rownum2/@Pagesize )
ELSE  (rownum2/@Pagesize )+rownum END PageIndex

from cte c
)
select processid,rownum2    
,(select max(PageIndex) from cte1) TotalPage
from cte1
where PageIndex=@Pageindex