T-SQL SELECT DISTINCT & ROW_NUMBER() OVER 排序问题

发布于 2024-08-22 03:05:02 字数 520 浏览 6 评论 0原文

我正在尝试使用 ROW_NUMBER() OVER 进行分页从视图中选择不同的行。当我将 ORDER BY 字段从 SMALLDATETIME 切换到 INT 时,我开始得到奇怪的结果:

SELECT RowId, Title, HitCount FROM
( SELECT DISTINCT Title, HitCount, ROW_NUMBER() OVER(ORDER BY HitCount DESC) AS RowId FROM ou_v_Articles T ) AS Temp
WHERE RowId BETWEEN 1 AND 5

此查询返回:

RowId | Title | HitCount
=======================
4  ---  9
1  ---  43
3  ---  11
2  ---  13
5  ---  0

结果显然顺序不正确。我不确定这里的问题是什么,但是当我删除 DISTINCT 时,它会正确排序它们。

谢谢。

I'm trying to select DISTINCT rows from a view using ROW_NUMBER() OVER for paging. When I switched the ORDER BY field from a SMALLDATETIME to INT I started getting weird results:

SELECT RowId, Title, HitCount FROM
( SELECT DISTINCT Title, HitCount, ROW_NUMBER() OVER(ORDER BY HitCount DESC) AS RowId FROM ou_v_Articles T ) AS Temp
WHERE RowId BETWEEN 1 AND 5

This query returns:

RowId | Title | HitCount
=======================
4  ---  9
1  ---  43
3  ---  11
2  ---  13
5  ---  0

The results are obviously not in the correct order. I'm not sure what the problem is here, but when I removed DISTINCT it orders them correctly.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

柏拉图鍀咏恒 2024-08-29 03:05:02

将 DISTINCT 应​​用于包含 ROW_NUMBER() 的列列表将始终导致每一行都是不同的,因为每行有一个 ROW_NUMBER。

Applying DISTINCT to a column list containing ROW_NUMBER() will always result in every row being distinct, as there is one ROW_NUMBER per row.

阳光的暖冬 2024-08-29 03:05:02

您获得的 RowId 值正确吗?也许您只需要外部查询上的 ORDER BY RowId 子句?

Is the RowId value you're getting correct? Perhaps you just need an ORDER BY RowId clause on the outer query?

向日葵 2024-08-29 03:05:02

您是否尝试过在外部选择上仅使用 order by 并删除 OVER 子句?

Have you tried just using an order by on the outer select and removing the OVER clause?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文