如何在此查询中使用 ROW_NUMBER? [关闭]
Posted
技术标签:
【中文标题】如何在此查询中使用 ROW_NUMBER? [关闭]【英文标题】:How can use ROW_NUMBER in this query? [closed] 【发布时间】:2016-09-15 07:49:25 【问题描述】:我是 SQL Server 的新手,有一个这样的查询:
SELECT distinct top 10 ExecuteDate
FROM [ClubEatc].[dbo].[GetOnlineBills]
ORDER BY ExecuteDate DESC
我应该在该查询中使用Row_Number
,我该如何编写该查询?
谢谢大家。
【问题讨论】:
我们不知道您要将ROW_NUMBER()
用于什么目的。
添加更多关于您的问题的详细信息,row_number 的顺序是什么以及您想要分区,如果是,那么在什么上?
【参考方案1】:
如果您希望每一行都有一个数字并且 ExecuteDate 应该是不同的:
WITH CTE AS
(
SELECT DISTINCT ExecuteDate FROM [ClubEatc].[dbo].[GetOnlineBills]
)
SELECT TOP 10 ExecuteDate, RN = ROW_NUMBER() OVER (ORDER BY ExecuteDate DESC)
FROM CTE
ORDER BY ExecuteDate DESC
或GROUP BY
:
SELECT TOP 10 ExecuteDate, RN = ROW_NUMBER() OVER (ORDER BY ExecuteDate DESC)
FROM [ClubEatc].[dbo].[GetOnlineBills]
GROUP BY ExecuteDate
ORDER BY ExecuteDate DESC
也许您想查看整个记录,但只查看每个 ExecuteDate-Group 的第一个。那么这个查询就可以工作了:
WITH CTE AS
(
SELECT ExecuteDate,
RN_DESC = ROW_NUMBER() OVER (PARTITION BY ExecuteDate
ORDER BY ExecuteDate DESC)
FROM [ClubEatc].[dbo].[GetOnlineBills]
)
SELECT TOP 10 ExecuteDate
FROM CTE
WHERE RN_DESC = 1
ORDER BY ExecuteDate DESC
您可以列出所有列,而不仅仅是ExecuteDate
列。但是ExecuteDate
是要分组的列,您还没有告诉我们要使用哪一列来对每个组进行排序,因此您想查看每个 ExecuteDate-group 的哪一行。所以目前这个查询返回每个组的任意行。将PARTITION BY ExecuteDate ORDER BY ExecuteDate DESC
更改为 f.e. PARTITION BY ExecuteDate ORDER BY AnotherDateOrIdColumn DESC
以获得更有意义的结果。
【讨论】:
谢谢,但是如何使用 where cluase,例如 where row=1? 你为什么需要它?那不是ROW_NUMBER()OVER(PARTITION BY ORDER BY ExecuteDate DESC)
。每个行号在上面都是不同的。如果您只想要第一行,请使用SELECT TOP 1
在我的数据库中返回两个不同的值:1395/6/17 和 1395/6/11,当使用 top 时只显示 1395/6/17,并希望访问 1395/6/11也很有价值。
@behzadrazzaqi:我编辑了我的答案,也许这就是你想要的【参考方案2】:
你可以使用:
SELECT TOP 10 ExecuteDate
FROM (
SELECT ExecuteDate,
ROW_NUMBER() over (PARTITION BY ExecuteDate ORDER BY ExecuteDate DESC) as RN
FROM [GetOnlineBills]
) as t
WHERE RN = 1
ORDER BY ExecuteDate DESC
或者:
SELECT TOP 10 ExecuteDate
FROM (
SELECT TOP 1 WITH TIES ExecuteDate
FROM [GetOnlineBills]
ORDER BY ROW_NUMBER() over (PARTITION BY ExecuteDate ORDER BY ExecuteDate DESC)
) as t
ORDER BY ExecuteDate DESC
【讨论】:
谢谢,但是这个 WHERE RN = 1 显示两行! 第二个查询呢?SELECT DISTINCT ExecuteDate FROM [GetOnlineBills]
它将返回多少行
SELECT DISTINCT ExecuteDate FROM [GetOnlineBills] 返回我两条记录,我想要访问所有行的位置,例如 row=1,row=2
你有两个不同的ExecuteDate
s,TOP 10
应该返回什么? :)【参考方案3】:
你的意思是这样的吗:
SELECT distinct top 10 ROW_NUMBER() OVER(ORDER BY ExecuteDate DESC), ExecuteDate
FROM [ClubEatc].[dbo].[GetOnlineBills]
ORDER BY ExecuteDate DESC
【讨论】:
以上是关于如何在此查询中使用 ROW_NUMBER? [关闭]的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Hibernate 中使用 row_number 函数编写查询?
如何在 Access 查询中显示行号,如 SQL 中的 ROW_NUMBER
如何在 Hive 查询中使用 row_number 来获取最新的用户登录?