10

有没有办法在 OVER ORDER BY 子句中指定多个列?

SELECT ROW_NUMBER() OVER(ORDER BY (A.Col1)) AS ID FROM MyTable A

以上工作正常,但尝试添加第二列不起作用。

SELECT ROW_NUMBER() OVER(ORDER BY (A.Col1, A.Col2)) AS ID FROM MyTable A

',' 附近的语法不正确。

4

2 回答 2

25

问题是列名周围的额外括号。这些都应该有效:

-- The standard way
SELECT ROW_NUMBER() OVER(ORDER BY A.Col1) AS ID FROM MyTable A
SELECT ROW_NUMBER() OVER(ORDER BY A.Col1, A.Col2) AS ID FROM MyTable A

-- Works, but unnecessary
SELECT ROW_NUMBER() OVER(ORDER BY (A.Col1), (A.Col2)) AS ID FROM MyTable A

此外,当您提出 SQL 问题时,您应该始终指定要查询的数据库。

于 2012-07-27T15:35:59.170 回答
2

没有括号。

SELECT ROW_NUMBER() OVER(ORDER BY A.Col1, A.Col2) AS ID FROM MyTable A 
于 2012-07-27T15:36:13.507 回答