SQL DENSE_RANK和PARTITION BY

时间:2019-07-03 18:59:58

标签: sql sql-server partition over-clause

我不完全了解以下列出的查询结果:

CREATE TABLE #tmpAccountsTable (ID INT PRIMARY KEY, AccountID INT, 

AccountName varchar(20), CompanyID int, CompanyName varchar(50))
INSERT INTO #tmpAccountsTable (ID, AccountID, AccountName, CompanyID, CompanyName)
SELECT 1 AS ID, 1 AS AccountID, 'ABC Account' AS AccountName, 1 AS CompanyID, 'Stark Enterprise' AS CompanyName UNION
SELECT 2 AS ID, 1 AS AccountID, 'ABC Account' AS AccountName, 1 AS CompanyID, 'Stark Enterprise' AS CompanyName UNION
SELECT 3 AS ID, 2 AS AccountID, 'DEF Account' AS AccountName, 1 AS CompanyID, 'Stark Enterprise' AS CompanyName UNION
SELECT 4 AS ID, 3 AS AccountID, 'GHI Account' AS AccountName, 1 AS CompanyID, 'Stark Enterprise' AS CompanyName UNION
SELECT 5 AS ID, 4 AS AccountID, 'JKL Account' AS AccountName, 1 AS CompanyID, 'Stark Enterprise' AS CompanyName UNION
SELECT 6 AS ID, 1 AS AccountID, 'ABC Account' AS AccountName, 1 AS CompanyID, 'Stark Enterprise' AS CompanyName UNION
SELECT 7 AS ID, 1 AS AccountID, 'ABC Account' AS AccountName, 1 AS CompanyID, 'Stark Enterprise' AS CompanyName UNION
SELECT 8 AS ID, 1 AS AccountID, 'ABC Account' AS AccountName, 1 AS CompanyID, 'Stark Enterprise' AS CompanyName UNION
SELECT 9 AS ID, 2 AS AccountID, 'DEF Account' AS AccountName, 1 AS CompanyID, 'Stark Enterprise' AS CompanyName

SELECT DENSE_RANK() OVER (PARTITION BY AccountID ORDER BY CompanyName) as AccountRANK, * FROM #tmpAccountsTable

DROP TABLE #tmpAccountsTable

执行上述操作,我得到以下结果集:

Result Set

根据我对SELECT DENSE_RANK() OVER (PARTITION BY AccountID ORDER BY CompanyName) as AccountRANK, * FROM #tmpAccountsTable的理解,应该为所有相同的AccountId创建一个分区,并且它们应该收到相同的DENSE_RANK()值,但是可以看出,这是并非如此。

我想念什么?

1 个答案:

答案 0 :(得分:4)

如果您想为每个AccountId分配一个单独的值,则该值应该是ORDER BY而不是PARTITION BY的一部分:

SELECT DENSE_RANK() OVER (ORDER BY AccountID, CompanyName) as AccountRANK, *
FROM #tmpAccountsTable;

PARTITION BY用于重置计数器,因此每个AccountId从1开始。然后对CompanyNames进行排序。因为它们都具有相同的值,所以结果为1