好的,因此基本上我DISTINCT通过使用变得无用ROW_NUMBER(),我需要避免这种情况,因为这会导致重复的结果(当然,除了唯一的数字!)
DISTINCT
ROW_NUMBER()
因此,我要寻找的是一个查询,该查询将保持相同,但没有重复的行,因为num是唯一的:
WITH t AS ( SELECT DISTINCT *, ROW_NUMBER() OVER (ORDER BY Date) AS num FROM Original_Import LEFT JOIN eqcas.dbo.BASE_PROXY_VIEW_WITHTARGET ON ADName = Targetuser WHERE (BaseProxy = 'agmc' OR ADName = 'agmc') AND (Commited IS NULL OR Commited = 0) ) SELECT DISTINCT ID, num, ADName, Description_User, Description_Amex, Amount, Date FROM t WHERE (t.BaseProxy = 'agmc' OR t.ADName = 'agmc') AND num BETWEEN 0 AND 20 AND (Commited IS NULL OR Commited = 0) ORDER BY Date
修复起来可能很琐碎,但由于我不是SQL Server专家,所以我不习惯这些内部查询等。
更新:是的,num用于分页。
好像我晚两年我最近的博客帖子大约ROW_NUMBER()是到SELECT什么DENSE_RANK()是对SELECT DISTINCT。您的CTE必须替换为:
SELECT
DENSE_RANK()
SELECT DISTINCT
WITH t AS ( SELECT DISTINCT *, DENSE_RANK() OVER (ORDER BY Date, ...) AS num FROM Original_Import LEFT JOIN eqcas.dbo.BASE_PROXY_VIEW_WITHTARGET ON ADName = Targetuser WHERE (BaseProxy = 'agmc' OR ADName = 'agmc') AND (Commited IS NULL OR Commited = 0) ) SELECT ...
在上面的查询中,DENSE_RANK()的ORDER BY子句将需要列出Original_Import和中的所有列BASE_PROXY_VIEW_WITH_TARGET,以重现与DISTINCT关键字相同的顺序。这将为每个重复的记录集分配一个准确的等级,这样DISTINCT可以再次工作。
ORDER BY
Original_Import
BASE_PROXY_VIEW_WITH_TARGET
在引用的博客文章中,我还包含了指向SQLFiddle的链接,该链接在一个更简单的示例中进行了说明。
SELECT DISTINCT v, DENSE_RANK() OVER (w) row_number FROM t WINDOW w AS (ORDER BY v) ORDER BY v, row_number