查询以显示返回的总行数,但结果集有限
Query to display total row count returned, but with a limited result set
出于质量检查目的,我需要提供错误记录样本以及错误记录总数。对于背景,此示例需要限制为 ~1000 条记录,因为查询结果存储在 Excel recordSet
对象中并输出到文本文件。这听起来很笨重(确实如此),但这是有原因的。
我知道我能做到:
SELECT TOP 1000
primaryKey
,expectedValue
,actualValue
,totalErrors
FROM errorTable
INNER JOIN (SELECT count(*) as totalErrors FROM errorTable) AS tmp
ON 1 = 1
但我想要一种更有效的方法,因为 errorTable
实际上是一个查找所有错误记录的子查询,并且计算量很大。
只需使用 window 函数:
SELECT TOP 1000 primaryKey, expectedValue, actualValue,
COUNT(*) OVER () as totalErrors
FROM errorTable;
您可以像这样进行交叉连接:
SELECT TOP 1000
primaryKey,
expectedValue,
actualValue,
tmp.totalErrors
FROM errorTablem, (SELECT count(*) as totalErrors FROM errorTable) AS tmp
出于质量检查目的,我需要提供错误记录样本以及错误记录总数。对于背景,此示例需要限制为 ~1000 条记录,因为查询结果存储在 Excel recordSet
对象中并输出到文本文件。这听起来很笨重(确实如此),但这是有原因的。
我知道我能做到:
SELECT TOP 1000
primaryKey
,expectedValue
,actualValue
,totalErrors
FROM errorTable
INNER JOIN (SELECT count(*) as totalErrors FROM errorTable) AS tmp
ON 1 = 1
但我想要一种更有效的方法,因为 errorTable
实际上是一个查找所有错误记录的子查询,并且计算量很大。
只需使用 window 函数:
SELECT TOP 1000 primaryKey, expectedValue, actualValue,
COUNT(*) OVER () as totalErrors
FROM errorTable;
您可以像这样进行交叉连接:
SELECT TOP 1000
primaryKey,
expectedValue,
actualValue,
tmp.totalErrors
FROM errorTablem, (SELECT count(*) as totalErrors FROM errorTable) AS tmp