开发者

Creating a computed column in a View. Is it possible?

开发者 https://www.devze.com 2023-02-16 02:17 出处:网络
My SQL view returns the following ID Name AA Gina AB George AC John I would like to add a computed column UpCounter so my view returns something like

My SQL view returns the following

ID Name
AA Gina
AB George
AC John

I would like to add a computed column UpCounter so my view returns something like

ID Name    UpCounter
AA Gin开发者_JAVA百科a    1
AB George  2
AC John    3

Is it possible?

UPDATE: The UpCounter is actually the row index


See the OVER Clause.

SELECT ID, Name, ROW_NUMBER() OVER(ORDER BY ID ASC) AS UpCounter
FROM xyz

Here's a use case:

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


You can use the ROW_NUMBER() function:

SELECT ROW_NUMBER() OVER (ORDER BY [ID]) AS MyIndex, 
       [ID], 
       [Name] 
FROM   MyTable

Also, note that a computed column is something different. A computed column is a "virtual column" on a table that just stores the forumla to be calculated then the field is selected. It does not take up row space.

0

精彩评论

暂无评论...
验证码 换一张
取 消