Urggggg!很长一段时间我一直在努力奋斗!我可以使用MySQL轻松实现,但不能使用SQL Server :(
以下是应该加在一起的简化表格。
通过使用内部联接语法组合所有这些,我必须编写一个查询,以便将来用于分页(顺便说一下,PHP)。假设我需要在2012-10-01和2012-10-30之间拍摄照片的所有ID,姓名和日期信息....每页20人。
在这里实现目标的最简单的查询是什么? (我没试过......但是它太错了因为我不习惯'不在'的东西......)
您可以忽略性能速度。
谢谢!
答案 0 :(得分:6)
我将在SQL Server 2005 +中执行此操作:
SELECT ID, Name, Photo, CreatedDate, rowNum, (rowNum / 20) + 1 as pageNum
FROM (
SELECT a.ID, a.Name, b.Photo, c.Created_Date
, Row_Number() OVER (ORDER BY c.Created_Date ASC) as rowNum
FROM a
JOIN b ON a.ID = b.ID
JOIN c ON c.photo = b.photo
WHERE c.Created_Date BETWEEN '2012-01-1' AND '2012-10-30'
) x
WHERE (rowNum / 20) + 1 = 1
请注意,我正在使用一个小整数除法技巧来计算页码。
由于2005年之前遗憾地没有row_number(),我会使用带有标识列的中间表:
SELECT a.ID, a.Name, b.Photo, c.Created_Date
, identity(int,1,1) as rowNum
INTO t
FROM a
JOIN b ON a.ID = b.ID
JOIN c ON c.photo = b.photo
WHERE c.Created_Date BETWEEN '2012-01-1' AND '2012-10-30'
ORDER BY c.Created_Date ASC
GO
ALTER TABLE t ADD pageNum AS rowNum / 20
GO
SELECT ID, Name, Photo, Created_Date, rowNum
FROM t
WHERE pageNum = 1
答案 1 :(得分:4)
这是我很久以前的做法..
SELECT * FROM (
SELECT TOP y * FROM (
SELECT TOP x * FROM sometable
ORDER BY somefield ASC
)
ORDER BY somefield DESC)
ORDER BY somefield
最里面的查询SELECT TOP x抓取前x行数, 第二个查询SELECT TOP y,得到x行的最后一个y,和 最外层的查询,SELECT *将结果按正确的顺序排列。
这是一篇博客文章,解释了它的工作原理这是我在2006年写的一篇博客文章,谈论它http://code.rawlinson.us/2006/12/t-sql-query-paging.html
tl; dr;帖子来自这一段:
例如,假设我们想要第一页,所以前20个结果。这很简单,只需使用SELECT TOP 20 ....但是第二页或后续页面怎么样?你怎么得到21-40项?它比你想象的要容易。你实际想要得到的是前x个结果的底部y。要以另一种方式查看,您需要向前排列前x个结果的前y个。
由您决定如何计算并向查询提供x和y值。
答案 2 :(得分:3)
Microsoft使用"OFFSET" and "FETCH"在SQL Server 2012及更高版本中添加了本机分页功能。您可以使用以下功能:
-- Skip the first 500 rows and return the next 100
SELECT *
FROM TableName
ORDER BY [ID]
OFFSET 500 ROWS
FETCH NEXT 100 ROWS ONLY;
对于OFFSET __
和FETCH NEXT __
子句,您可以指定常量值(如上所述),也可以指定变量,表达式或常量标量子查询。
答案 3 :(得分:2)
使用Sql Server 2008 + AdventureWorks数据库
尝试此操作DECLARE @PageIndex INT, @RowsPerPage INT
DECLARE @StartRow INT, @EndRow INT;
SET @PageIndex = 1;
SET @RowsPerPage = 500;
SET @StartRow = ((@PageIndex - 1) * @RowsPerPage) + 1;
SET @EndRow = @StartRow + @RowsPerPage - 1;
--append#1
WITH PAGE_ROWS
AS
(
SELECT ROW_NUMBER() OVER(ORDER BY OrderDate DESC, SalesOrderNumber ASC) AS ROW_NO
, COUNT(*) OVER() AS TOTAL_ROWS
, *
FROM(
--working query
SELECT S.SalesOrderID
, S.SalesOrderNumber
, S.OrderDate
, S.DueDate
, S.ShipDate
, S.Status
, S.PurchaseOrderNumber
, C.AccountNumber
, P.FirstName, P.MiddleName, P.LastName
FROM [Sales].[SalesOrderHeader] AS S
LEFT OUTER JOIN [Sales].[Customer] AS C ON C.CustomerID=S.CustomerID
LEFT OUTER JOIN [Person].[Person] AS P ON P.BusinessEntityID=C.PersonID
--append#2
) AS Src)
SELECT CEILING(TOTAL_ROWS/ CAST(@RowsPerPage AS DECIMAL(20,2))) AS TOTAL_PAGES
,*
FROM PAGE_ROWS
WHERE ROW_NO BETWEEN @StartRow AND @EndRow
ORDER BY OrderDate DESC, SalesOrderNumber ASC
答案 4 :(得分:1)
ALTER Proc [dbo].[Sp_PagingonTable]
@SearchText varchar(255) = null,
@ChannelName varchar(255)= null,
@ChannelCategory varchar(255)= null,
@ChannelType varchar(255)= null,
@PageNo int,
@PageSize int,
@TotalPages int output
As
DECLARE @VariableTable TABLE
(
Rownumber INT,
ReferralHierarchyKey BIGINT,
ReferralID VARCHAR(255),
ChannelDetail VARCHAR(255),
ChannelName VARCHAR(255),
ChannelCategory VARCHAR(255),
ChannelType VARCHAR(255)
)
/*---Inserting Data into variable Table-------------*/
INSERT INTO @VariableTable
SELECT
ROW_NUMBER() OVER(ORDER BY [ColumnID) as Rownumber,*
FROM [dbo].[TableName]
WHERE (@SearchText IS NULL OR ChannelDetail LIKE '%' + @SearchText + '%') And (@ChannelName IS NULL OR ChannelName = @ChannelName )
/*--Applying Paging on filter Table--*/
SELECT
ReferralID
,ChannelDetail
,ChannelName
,ChannelCategory
,ChannelType
FROM
@VariableTable
WHERE Rownumber between (((@PageNo -1) *@PageSize)+1) and @PageNo * @PageSize
/*--Getting Total Pages After filter Table---*/
SELECT @TotalPages = (Count(*) + @PageSize - 1)/@PageSize FROM @VariableTable
SELECT @TotalPages
答案 5 :(得分:1)
我喜欢Taha Siddiqui的答案,除了它需要修改传入的查询,它不适用于我必须使用的SQL UNION语句,因为前同事做出了一些非常糟糕的设计决策。
通用SQL Server查询是:
SELECT * FROM (
select ROW_NUMBER() OVER (order by ID) as row_num, * FROM (
<<Put Your Query Here>>
) AS tempTable1
) AS tempTable2 WHERE row_num >= ((pageNum -1) * pageSize) AND row_num < ((pageNum -1) * pageSize) + pageSize;
我创建了一个假定基于一个分页的Java函数:
public static String buildPagingQuery(String sqlStr, String sortExpression, int pageNum, int pageSize) {
if (StringUtils.isBlank(sortExpression)) { //NOTE: uses org.apache.commons.lang.StringUtils
sortExpression = " (select 0)";
}
int startIndex = ((pageNum - 1) * pageSize) + 1;
int endIndex = startIndex + pageSize;
StringBuilder sb = new StringBuilder();
sb.append("SELECT * FROM (");
sb.append("SELECT ROW_NUMBER() OVER (ORDER BY ");
sb.append(sortExpression);
sb.append(") as row_num, * FROM (");
sb.append(sqlStr);
sb.append(") as tempTable1 ");
sb.append(") AS tempTable2 ");
sb.append("WHERE row_num >= ").append(startIndex);
sb.append(" AND row_num < ").append(endIndex);
return sb.toString();
}
我还没有在大桌子上检查过表现。
答案 6 :(得分:1)
我们可以通过CTE(通用表表达式)实现相同的功能。首先,我们需要设置当前页码和需要获取的结果的偏移量,然后我们必须通过ROW_NUMBER对结果集进行排序并存储通过使用cte功能获得结果。然后使用页面大小和行号偏移量过滤结果。 SQL查询如下
DECLARE @PageSize INT=1 ,@PageNumber INT=2
DECLARE @Offset int =(@PageSize * (@PageNumber - 1))+1
;WITH Results_CTE AS
(
SELECT *,
ROW_NUMBER() OVER (ORDER BY FieldName) AS RowNum
FROM TABLENAME
)
SELECT *
FROM Results_CTE
WHERE RowNum>=@Offset AND RowNum < @Offset + @PageSize
END
https://amonghorizon.blogspot.com/2020/07/sql-server-query-for-pagination-control.html
答案 7 :(得分:0)
您可以使用以下类中的方法
internal class PagingHelper
{
public static String ParseQueryForPagingAndSorting(String strSQL, string SortExpression, int StartIndex, int EndIndex)
{
if (String.IsNullOrEmpty(SortExpression))
SortExpression = " (select 0)";
StringBuilder sb = new StringBuilder();
sb.Append("select * from (");
sb.Append(" select ROW_NUMBER() OVER (ORDER BY " + SortExpression + ") AS row_num,");
int index = strSQL.ToLower().IndexOf('t', 0);
sb.Append(strSQL.Substring(index + 2));
sb.Append(")");
sb.Append(" AS TempTable");
sb.Append(" where row_num>=" + StartIndex.ToString() + " AND row_num<=" + EndIndex.ToString());
return sb.ToString();
}
public static String ParseQueryForCount(String strSQL)
{
StringBuilder sb = new StringBuilder();
sb.Append("select count(*) from");
sb.Append("(");
sb.Append(strSQL);
sb.Append(")");
sb.Append(" AS TempTable");
return sb.ToString();
}
}
答案 8 :(得分:-1)
我发现另一种方法是在Sql server 2012中执行此操作
http://raresql.com/2012/07/01/sql-paging-in-sql-server-2012-using-order-by-offset-and-fetch-next/