这个sql语句怎么先排序后分页
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了这个sql语句怎么先排序后分页相关的知识,希望对你有一定的参考价值。
SELECT g_ID,g_Text,g_PublishID,g_PublishTime FROM
(SELECT ROW_NUMBER() OVER (ORDER BY g_id) AS
RowNumber,*,(select count(*) from dp_Praise
where dp_Praise.p_textID = dp_Gossip.g_id) as cnt FROM dp_Gossip) A
WHERE RowNumber between 0 and 20 * 1 order by cnt desc
@TableSource VARCHAR(100), --表名或视图表
@SearchCondition VARCHAR(2000), --查询条件
@OrderExpression VARCHAR(1000), --排序表达式
@PageIndex INT = 1, --页号,从0开始
@PageSize INT = 10 --页尺寸
AS
BEGIN
IF @SelectList IS NULL OR LTRIM(RTRIM(@SelectList)) = ''
BEGIN
SET @SelectList = '*'
END
PRINT @SelectList
SET @SearchCondition = ISNULL(@SearchCondition,'')
SET @SearchCondition = LTRIM(RTRIM(@SearchCondition))
IF @SearchCondition <> ''
BEGIN
IF UPPER(SUBSTRING(@SearchCondition,1,5)) <> 'WHERE'
BEGIN
SET @SearchCondition = 'WHERE ' + @SearchCondition
END
END
PRINT @SearchCondition
SET @OrderExpression = ISNULL(@OrderExpression,'')
SET @OrderExpression = LTRIM(RTRIM(@OrderExpression))
IF @OrderExpression <> ''
BEGIN
IF UPPER(SUBSTRING(@OrderExpression,1,5)) <> 'WHERE'
BEGIN
SET @OrderExpression = 'ORDER BY ' + @OrderExpression
END
END
PRINT @OrderExpression
IF @PageIndex IS NULL OR @PageIndex < 1
BEGIN
SET @PageIndex = 1
END
PRINT @PageIndex
IF @PageSize IS NULL OR @PageSize < 1
BEGIN
SET @PageSize = 10
END
PRINT @PageSize
DECLARE @SqlQuery VARCHAR(4000)
SET @SqlQuery='SELECT '+@SelectList+',RowNumber
FROM
(SELECT ' + @SelectList + ',ROW_NUMBER() OVER( '+ @OrderExpression +') AS RowNumber
FROM '+@TableSource+' '+ @SearchCondition +') AS RowNumberTableSource
WHERE RowNumber BETWEEN ' + CAST(((@PageIndex - 1)* @PageSize+1) AS VARCHAR)
+ ' AND ' +
CAST((@PageIndex * @PageSize) AS VARCHAR)
ORDER BY ' + @OrderExpression
PRINT @SqlQuery
SET NOCOUNT ON
EXECUTE(@SqlQuery)
SET NOCOUNT OFF
你参考下 参考技术B 分页与排序是不分开的。
你可以用
;with cte as(
select rn=row_number() over(order by xxxx) ,* from tb ;
)
select * from cte where rn between xxx and xxx;追问
现在有dp_Gossip,dp_Praise两个表,我要根据dp_praise里面数据最多的进行排序,关联字段dp_Praise.p_textID = dp_Gossip.g_id ,排序好后分页,读取dp_Gossip的数据
追答是可以的。
;with cte as (
select rn=row_number() over(order by ct),* from (
select a.* from dp_Gossip a join (select g_id,count(1) as ct from dp_Praise group by g_id) b on a.g_id=b.g_id
)
)
select * from cte where rn between xxx and yyy;
--不知道我理解对没。
亲,你远程帮我弄好吗?都急死我了.加你qq方便吗?我的QQ:401063361
追答不方便,上班。这种你自己测试修改一下应该就可以的。
追问好的,谢谢.
本回答被提问者和网友采纳 参考技术C SELECT 字段 FROM 表名 where 条件 分页 默认排序就行啦追问我想先排序好,在分页.
追答我知道,你先将全部的数据排好序,在分页,
追问是的,那个sql语句应该怎么写呢?
能加QQ吗?我的qq:401063361
以上是关于这个sql语句怎么先排序后分页的主要内容,如果未能解决你的问题,请参考以下文章