如何在此查询中使用ROW_NUMBER?

时间:2016-09-15 07:49:26

标签: sql sql-server tsql window-functions

我是SQL Server的新用户,并且有一个查询:

GDB

我应该在该查询中使用SELECT distinct top 10 ExecuteDate FROM [ClubEatc].[dbo].[GetOnlineBills] ORDER BY ExecuteDate DESC ,我该如何编写该查询?

谢谢大家。

3 个答案:

答案 0 :(得分: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组的哪一行。所以目前这个查询返回每个组的任意行。将PARTITION BY ExecuteDate ORDER BY ExecuteDate DESC更改为f.e. PARTITION BY ExecuteDate ORDER BY AnotherDateOrIdColumn DESC以获得更有意义的结果。

答案 1 :(得分:1)

你的意思是这样的:

SELECT distinct  top 10 ROW_NUMBER() OVER(ORDER BY ExecuteDate DESC), ExecuteDate  
FROM [ClubEatc].[dbo].[GetOnlineBills]  
ORDER BY ExecuteDate  DESC

答案 2 :(得分:1)

您可以使用:

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