Home > database >  Assigning a letter column to each row
Assigning a letter column to each row

Time:12-22

Let's say I have a data set that is simply a column of ints. For example:

CREATE TABLE #nums
(    
    Number int NOT NULL 
)

INSERT INTO #nums 
VALUES (5), 
(7), 
(6),
(9)

I would like to write a query that would return this data along with a second column that consists of the letters, 'A', 'B', 'C' etc. The lowest number should match to 'A' and the highest number should match to the final letter in the sequence. The number of rows in the initial table will vary but will never be more than 12.

CodePudding user response:

Perhaps this will help. The window function row_number() over() in concert with the char() function

Example

Select *
      ,NewVal = char(64 row_number() over (order by Number))
 From  #nums

Results

Number  NewVal
5       A
6       B
7       C
9       D
  • Related