我的SQL视图返回以下内容
ID Name
AA Gina
AB George
AC John
我想添加一个计算列UpCounter
,以便我的视图返回类似
ID Name UpCounter
AA Gina 1
AB George 2
AC John 3
有可能吗?
UPDATE: UpCounter实际上是行索引
答案 0 :(得分:4)
请参阅OVER Clause。
SELECT ID, Name, ROW_NUMBER() OVER(ORDER BY ID ASC) AS UpCounter
FROM xyz
这是一个用例:
WITH x AS (
SELECT 'AA' as ID, 'Gina' as Name
UNION
SELECT 'AB' as ID, 'George' as Name
UNION
SELECT 'AC' as ID, 'John' as Name
)
SELECT ID, Name, ROW_NUMBER() OVER(ORDER BY ID ASC) AS UpCounter
FROM x
答案 1 :(得分:1)
您可以使用ROW_NUMBER()函数:
SELECT ROW_NUMBER() OVER (ORDER BY [ID]) AS MyIndex,
[ID],
[Name]
FROM MyTable
另外,请注意计算列是不同的。计算列是表上的“虚拟列”,其仅存储要计算的论坛,然后选择该字段。它不占用行空间。