两种选择中的哪一种更好?
ROW_NUMBER() OVER (PARTITION BY...)
或
COUNT(1) OVER (PARTITION BY ...)
我找不到任何这样的问题。
修改
DBMS: SQL-SERVER (version >= 2008)In my case the over partition is guaranteed by a single field: ROW_NUMBER() OVER (PARTITION BY ELEMENT ORDER BY EMPLOYEE) COUNT(1) OVER (PARTITION BY ELEMENT ORDER BY EMPLOYEE)
ELEMENT EMPLOYEE ROW_NUMBER COUNT
0000001 00000003 1 1 0000001 00000004 2 2 0000001 00000005 3 3 0000003 00000045 1 1 0000003 00000046 2 2
答案 0 :(得分:2)
COUNT(1)
列中的同一组值重复时, ORDER BY
的行为会有所不同。
以下是SQL Server的一个示例:
IF OBJECT_ID('tempdb..#Example') IS NOT NULL
DROP TABLE #Example
CREATE TABLE #Example (
Number INT,
GroupNumber INT)
INSERT INTO #Example (
Number,
GroupNumber)
VALUES
(NULL, 1),
(100, 1),
(101, 1),
(102, 1),
(103, 1),
(NULL, 2),
(NULL, 2),
(NULL, 2),
(200, 2),
(201, 2),
(202, 2),
(300, 3),
(301, 3),
(301, 3),
(301, 3),
(302, 3)
SELECT
E.*,
RowNumber = ROW_NUMBER() OVER (PARTITION BY E.GroupNumber ORDER BY E.Number ASC),
CountOver = COUNT(1) OVER (PARTITION BY E.GroupNumber ORDER BY E.Number ASC)
FROM
#Example AS E
结果:
Number GroupNumber RowNumber CountOver
----------- ----------- -------------------- -----------
NULL 1 1 1
100 1 2 2
101 1 3 3
102 1 4 4
103 1 5 5
NULL 2 1 3 Here
NULL 2 2 3
NULL 2 3 3
200 2 4 4
201 2 5 5
202 2 6 6
300 3 1 1
301 3 2 4 Here
301 3 3 4
301 3 4 4
302 3 5 5
这是因为它是一个计数而不是行数。你应该使用适合你需要的那个。