我正在尝试在MSSQL中进行一些基本的分页。我遇到的问题是我正在排序(可能)具有相似值的行上的分页,并且ORDER BY子句返回“随机”结果,但效果不佳。
例如。
如果我有三行,并且我按“评级”对它们进行排序,并且所有评级都是='5' - 这些行似乎会“随机”排序。我如何制作它以便每次都以相同的顺序显示行?
我尝试按照上次编辑该字段的日期时间对其进行排序,但“评级”是反向排序的,并且再次不起作用我希望它如何工作。
这是我到目前为止使用的SQL。我知道如果没有这些数据就会有点困惑......任何帮助都会很棒。
SELECT * FROM
(
SELECT
CAST(grg.defaultthumbid AS VARCHAR) + '_' +
CAST(grg.garageid AS VARCHAR) AS imagename,
(
SELECT COUNT(imageid)
FROM dbo.images im (nolock)
WHERE im.garageid = grg.garageid
) AS piccount,
(
SELECT COUNT(commentid)
FROM dbo.comments cmt (nolock)
WHERE cmt.garageid = grg.garageid
) AS commentcount,
grg.GarageID, mk.make, mdl.model, grg.year,
typ.type, usr.username, grg.content,
grg.rating, grg.DateEdit as DateEdit,
ROW_NUMBER() OVER (ORDER BY Rating DESC) As RowIndex
FROM
dbo.garage grg (nolock)
LEFT JOIN dbo.users (nolock) AS usr ON (grg.userid = usr.userid)
LEFT JOIN dbo.make (nolock) AS mk ON (grg.makeid = mk.makeid)
LEFT JOIN dbo.type (nolock) AS typ ON (typ.typeid = mk.typeid)
LEFT JOIN dbo.model (nolock) AS mdl ON (grg.modelid = mdl.modelid)
WHERE
typ.type = 'Automobile' AND
grg.defaultthumbid != 0 AND
usr.username IS NOT NULL
) As QueryResults
WHERE
RowIndex BETWEEN (2 - 1) * 25 + 2 AND 2 * 25
ORDER BY
DateEdit DESC
答案 0 :(得分:3)
尝试两者订购,例如: 按订单排序DESC,DateEdit ASC
答案 1 :(得分:1)
查询首先按[Rating]对行进行编号,然后按[DateEdit]重新排序结果。可能不是你想要的。按[RowIndex]排序ASC应该将其排序。
ROW_NUMBER() OVER (ORDER BY [Rating] DESC) As [RowIndex]
...
ORDER BY [RowIndex]