返回在with语句中选择的行

时间:2014-06-26 16:23:10

标签: sql sql-server

我有一个类似这样的SQL语句

WITH [ResultPage] AS (
SELECT sub.id as id, ROW_NUMBER() OVER (ORDER BY [TAG].[Name] ASC, [TAG].[ID] ASC) As [RowID], [sub].[hasPending]
    FROM
    (SELECT t.[ID], p.[TagID],(CASE WHEN p.[TagID] is not null THEN 1 ELSE 0 END) AS [hasPending]
    FROM [Tag] AS t
     full outer Join [TagPending] AS p On t.[ID] = p.[TagID]
     GROUP BY t.[ID],p.[TagID]
    ) AS [sub]
     inner Join [Tag] On [Tag].[ID] = sub.[ID]
)

SELECT [ResultPage].[RowID], [Tag].[ID] As [Tag^ID], [Tag].[Name] As [Tag^Name]
 FROM [ResultPage] 
INNER JOIN [Tag] ON ([Tag].[ID] = [ResultPage].[TagID]) 
INNER JOIN  [TagPending] ON ([TagPending].[TagID] = [KbResultPage].[TagID]) 
WHERE (([ResultPage].[RowID] BETWEEN 1 AND 50)
)
ORDER BY [ResultPage].[RowID] ASC

可以看出,select max一次返回50行,但是我需要知道在WITH语句中找到的总行数。我只需要一次计数就可以再次运行它,但是如果有办法一次性完成这两项工作可能会很好。

1 个答案:

答案 0 :(得分:3)

您可以在WITH语句

中使用COUNT(*)OVER()
WITH [ResultPage] AS (
SELECT COUNT(*) OVER() AS totalRows,  
sub.id as id, ROW_NUMBER() OVER (ORDER BY [TAG].[Name] ASC, [TAG].[ID] ASC) As         [RowID], [sub].[hasPending] 
   FROM 
  (SELECT t.[ID], p.[TagID],(CASE WHEN p.[TagID] is not null THEN 1 ELSE 0 END) AS  [hasPending]
   FROM [Tag] AS t
   full outer Join [TagPending] AS p On t.[ID] = p.[TagID]
   GROUP BY t.[ID],p.[TagID]
   ) AS [sub]
inner Join [Tag] On [Tag].[ID] = sub.[ID]
)

SELECT
 [ResultPage].totalRows,
 [ResultPage].[RowID], [Tag].[ID] As [Tag^ID], [Tag].[Name] As [Tag^Name]
FROM [ResultPage] 
INNER JOIN [Tag] ON ([Tag].[ID] = [ResultPage].[TagID]) 
INNER JOIN  [TagPending] ON ([TagPending].[TagID] = [KbResultPage].[TagID]) 
WHERE ([ResultPage].[RowID] BETWEEN 1 AND 50)
ORDER BY [ResultPage].[RowID] ASC